9.7 利用装饰器强制函数上的类型检查

    在演示实际代码前,先说明我们的目标:能对函数参数类型进行断言,类似下面这样:

    下面是使用装饰器技术来实现 :

    1. from inspect import signature
    2. from functools import wraps
    3.  
    4. def typeassert(*ty_args, **ty_kwargs):
    5. def decorate(func):
    6. # If in optimized mode, disable type checking
    7. if not __debug__:
    8. return func
    9.  
    10. # Map function argument names to supplied types
    11. sig = signature(func)
    12. bound_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
    13.  
    14. @wraps(func)
    15. def wrapper(*args, **kwargs):
    16. bound_values = sig.bind(*args, **kwargs)
    17. # Enforce type assertions across supplied arguments
    18. for name, value in bound_values.arguments.items():
    19. if name in bound_types:
    20. if not isinstance(value, bound_types[name]):
    21. raise TypeError(
    22. 'Argument {} must be {}'.format(name, bound_types[name])
    23. )
    24. return func(*args, **kwargs)
    25. return wrapper

    可以看出这个装饰器非常灵活,既可以指定所有参数类型,也可以只指定部分。并且可以通过位置或关键字来指定参数类型。下面是使用示例:

    1. >>> @typeassert(int, z=int)
    2. ... def spam(x, y, z=42):
    3. ... print(x, y, z)
    4. ...
    5. >>> spam(1, 2, 3)
    6. 1 2 3
    7. >>> spam(1, 'hello', 3)
    8. 1 hello 3
    9. >>> spam(1, 'hello', 'world')
    10. Traceback (most recent call last):
    11. File "<stdin>", line 1, in <module>
    12. File "contract.py", line 33, in wrapper
    13. TypeError: Argument z must be <class 'int'>
    14. >>>

    这节是高级装饰器示例,引入了很多重要的概念。

    首先,装饰器只会在函数定义时被调用一次。有时候你去掉装饰器的功能,那么你只需要简单的返回被装饰函数即可。下面的代码中,如果全局变量 debug 被设置成了False(当你使用-O或-OO参数的优化模式执行程序时),那么就直接返回未修改过的函数本身:

    1. >>> from inspect import signature
    2. >>> def spam(x, y, z=42):
    3. ... pass
    4. ...
    5. >>> sig = signature(spam)
    6. >>> print(sig)
    7. (x, y, z=42)
    8. >>> sig.parameters
    9. mappingproxy(OrderedDict([('x', <Parameter at 0x10077a050 'x'>),
    10. ('y', <Parameter at 0x10077a158 'y'>), ('z', <Parameter at 0x10077a1b0 'z'>)]))
    11. >>> sig.parameters['z'].name
    12. 'z'
    13. >>> sig.parameters['z'].default
    14. 42
    15. <_ParameterKind: 'POSITIONAL_OR_KEYWORD'>
    16. >>>

    装饰器的开始部分,我们使用了 方法来执行从指定类型到名称的部分绑定。下面是例子演示:

    1. >>> bound_types = sig.bind_partial(int,z=int)
    2. >>> bound_types
    3. <inspect.BoundArguments object at 0x10069bb50>
    4. >>> bound_types.arguments
    5. OrderedDict([('x', <class 'int'>), ('z', <class 'int'>)])
    6. >>>

    在这个部分绑定中,你可以注意到缺失的参数被忽略了(比如并没有对y进行绑定)。不过最重要的是创建了一个有序字典 bound_types.arguments 。这个字典会将参数名以函数签名中相同顺序映射到指定的类型值上面去。在我们的装饰器例子中,这个映射包含了我们要强制指定的类型断言。

    在装饰器创建的实际包装函数中使用到了 sig.bind() 方法。 跟 bind_partial() 类似,但是它不允许忽略任何参数。因此有了下面的结果:

    使用这个映射我们可以很轻松的实现我们的强制类型检查:

    1. >>> for name, value in bound_values.arguments.items():
    2. ... if name in bound_types.arguments:
    3. ... if not isinstance(value, bound_types.arguments[name]):
    4. ... raise TypeError()
    5. ...
    6. >>>

    不过这个方案还有点小瑕疵,它对于有默认值的参数并不适用。比如下面的代码可以正常工作,尽管items的类型是错误的:

    1. >>> @typeassert(int, list)
    2. ... def bar(x, items=None):
    3. ... if items is None:
    4. ... items = []
    5. ... items.append(x)
    6. ... return items
    7. >>> bar(2)
    8. [2]
    9. >>> bar(2,3)
    10. Traceback (most recent call last):
    11. File "<stdin>", line 1, in <module>
    12. File "contract.py", line 33, in wrapper
    13. TypeError: Argument items must be <class 'list'>
    14. >>> bar(4, [1, 2, 3])
    15. >>>

    一个可能的原因是如果使用了函数参数注解,那么就被限制了。如果注解被用来做类型检查就不能做其他事情了。而且 不能再用于使用注解做其他事情的函数了。而使用上面的装饰器参数灵活性大多了,也更加通用。

    可以在PEP 362以及 模块中找到更多关于函数参数对象的信息。在9.16小节还有另外一个例子。

    原文: