简单的动态类型检查 - python

是否有“标准”方式在Python中添加简单的动态类型检查,例如:

def add(a, b):
    # Argument type check
    check(a, int)
    check(b, int)
    # Calculate
    res = a + b
    # Result type check and return 
    check(res, int)
    return res

如果类型不匹配,则check可能会引发异常。

我当然可以自己做一些事情,做isinstance(..., ...)type(...) == ...,但是我想知道是否有一些用于这种类型检查的“标准”模块。

如果还可以执行更复杂的类型检查,例如检查参数是str还是int,或者例如liststr,那将是很好的。

我知道它在某种程度上违背了Python的鸭子类型原则,但是由于类型错误的参数,我花了几个小时进行调试,而且它是一个大型程序,因此原因中出现了许多嵌套调用。

python大神给出的解决方案

您可以使用装饰器功能。像这样:

def typecheck(*types):
    def __f(f):
        def _f(*args):
            for a, t in zip(args, types):
                if not isinstance(a, t):
                    print "WARNING: Expected", t, "got", a
            return f(*args)
        return _f
    return __f

@typecheck(int, str, int)
def foo(a, b, c):
    pass    

foo(1, "bar", 5)
foo(4, None, "string")

输出(第二个呼叫)是

WARNING: Expected <type 'str'>, got None 
WARNING: Expected <type 'int'>, got 'string' 

就目前而言,这不适用于关键字参数。

编辑:经过一番搜索,我发现一些更复杂的类型检查装饰器(1) (2)也支持关键字参数和返回类型。