基本上,foo()
期望的参数应该作为int
传递,但是有可能有人将它作为str
传递(如果str
可以转换为int
,这也是有效的)。这就是我想到的:
def foo(input_argument):
func_name = 'foo'
if type(input_argument) is not int or type(input_argument) is not str:
print(
'%s: "input_argument" expects int/str, not %s' % (
func_name,
type(input_argument)
)
)
return None
try:
input_argument= int(input_argument)
except:
print(
'%s: "input_argument" expects number in str/int format' % func_name
)
return None
有什么东西是内置的,可以简化这一点在一个更python的方式?你知道吗
编辑:布尔类型应视为无效
您最终可以使用一些数据验证库,比如Cerberus,但正如jonsharpe在一篇评论中所说的,常见的方法是让python通过简单地将输入转换成整数来处理错误。你知道吗
只要做:
请看那里,了解更多关于这个主题的信息:https://stackoverflow.com/a/154156/4279120
您可以使用type hints来获得IDE对类型的支持(IDE会告诉您是否传递了错误的类型)。。。无论如何,没有什么可以阻止在运行时传递错误的类型,因此您可以在下面的代码段中检查它,如果接收到的对象不是预期的对象,则引发
ValueError
:我觉得你把事情搞得太复杂了
或者有更好的错误处理
相关问题 更多 >
编程相关推荐