检查Python中的函数参数的最佳方法 [英] Best way to check function arguments in Python
问题描述
我在寻找一种有效的方法来检查一个Python函数的变量。例如,我想检查参数类型和值。是否有此模块?或者我应该使用类似装饰,或任何特定的成语?
DEF my_function(A,B,C):
的一个例子的功能,我想检查的论点。
#检查一个是一个int
#检查0℃; B< 10
#检查c不是一个空字符串
最Python化成语是明确的文件的什么函数需要,然后就尝试使用任何被传递到你的函数,要么让例外传播或正好赶上属性错误,并提出一个类型错误
来代替。因为它违背动态类型的类型检查应避免尽可能。值测试可确定 - 根据上下文
在这里验证真正有意义的地方是在系统或子系统的切入点,如Web窗体,命令行参数等其他地方一样,只要你的功能得到妥善记载,这是主叫方的责任通过适当的参数
I'm looking for an efficient way to check variables of a python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?
def my_function(a, b, c):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError
instead. Type-checking should be avoided as much as possible as it goes against dynamic typing. Value testing can be OK – depending on the context.
The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.
这篇关于检查Python中的函数参数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!