检查函数参数的最佳方法是什么?

86

我正在寻找一种高效的方法来检查Python函数的变量。例如,我想检查参数类型和值。是否有适用于此的模块?或者应该使用像装饰器这样的东西,或者任何特定的习惯用法吗?

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
14个回答

0
如果您想一次性检查**kwargs*args以及普通参数,可以在函数定义中的第一条语句中使用locals()函数来获取参数字典。
然后使用type()来检查参数,例如在迭代字典时。
def myfunc(my, args, to, this, function, **kwargs):
    d = locals()
    assert(type(d.get('x')) == str)
    for x in d:
        if x != 'x':
            assert(type(d[x]) == x
    for x in ['a','b','c']:
        assert(x in d)

    whatever more...

0
如果您想为多个函数进行验证,可以像这样在装饰器中添加逻辑:
def deco(func):
     def wrapper(a,b,c):
         if not isinstance(a, int)\
            or not isinstance(b, int)\
            or not isinstance(c, str):
             raise TypeError
         if not 0 < b < 10:
             raise ValueError
         if c == '':
             raise ValueError
         return func(a,b,c)
     return wrapper

并使用它:

@deco
def foo(a,b,c):
    print 'ok!'

希望这能帮到你!


3
如果你_真的_坚持使用类型检查,请至少使用isinstance,并引发TypeError异常。 - bruno desthuilliers
@brunodesthuilliers 谢谢你提醒我!我会编辑我的回答。 - Paulo Bu
为什么不使用 return func(a, b, c) - glglgl
1
@PauloBu:glglgl 的意思是你的 rapper 不仅应该调用装饰函数,还应该返回函数调用的结果。 - bruno desthuilliers
1
我在这里说这句话可能会惹上麻烦,但如果你确实需要大量的类型检查,也可以考虑使用其他编程语言。 - Christophe Roussy
显示剩余2条评论

0

这不是针对您的问题的解决方案,但如果您想要限制函数调用到某些特定的参数类型,那么你必须使用 PROATOR {Python函数原型验证器}。您可以参考以下链接。https://github.com/mohit-thakur-721/proator


-1
def myFunction(a,b,c):
"This is an example function I'd like to check arguments of"
    if type( a ) == int:
       #dostuff
    if 0 < b < 10:
       #dostuff
    if type( C ) == str and c != "":
       #dostuff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接