小智 11
我从未见过野外使用的这个功能.但是,我在为USENIX编写的Python 3文章中探讨了函数注释的一个潜在用途;登录:用于执行合同.例如,您可以这样做:
from functools import wraps
def positive(x):
'must be positive'
return x > 0
def negative(x):
'must be negative'
return x < 0
def ensure(func):
'Decorator that enforces contracts on function arguments (if present)'
return_check = func.__annotations__.get('return',None)
arg_checks = [(name,func.__annotations__.get(name))
for name in func.__code__.co_varnames]
@wraps(func)
def assert_call(*args):
for (name,check),value in zip(arg_checks,args):
if check:
assert check(value),"%s %s" % (name, check.__doc__)
result = func(*args)
if return_check:
assert return_check(result),"return %s" % (return_check.__doc__)
return result
return assert_call
# Example use
@ensure
def foo(a:positive, b:negative) -> positive:
return a-b
Run Code Online (Sandbox Code Playgroud)
如果你这样做,你会看到这样的行为:
>>> foo(2,-3)
5
>>> foo(2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ensure.py", line 22, in assert_call
assert check(value),"%s %s" % (name, check.__doc__)
AssertionError: b must be negative
Run Code Online (Sandbox Code Playgroud)
我应该注意,上面的示例需要充实,以便使用默认参数,关键字参数和其他详细信息正常工作.这只是一个想法的草图.
现在,不管这是不是一个好主意,我只是不知道.我倾向于同意Brandon认为缺乏可组合性是一个问题 - 特别是如果注释开始被不同的库用于不同的目的.我也想知道这个合同想法之类的东西是不是可以通过装饰者完成的.例如,制作一个像这样使用的装饰器(实现作为练习):
@ensure(a=positive,b=negative)
def foo(a,b):
return a-b
Run Code Online (Sandbox Code Playgroud)
历史记录,我总是觉得功能注释是关于Python社区10多年前的"可选静态类型"讨论的产物.不管这是不是最初的动机,我只是不知道.
我会玩这个傻瓜,并建议不要使用这个功能.希望有一天它会被删除.到目前为止,Python在部署有吸引力,正交且可堆叠的功能方面做得非常出色 - 函数装饰器就是一个很好的例子:如果我使用三个不同的库,都希望我装饰我的函数,结果看起来相当干净:
@lru_cache(max_items=5)
@require_basic_auth
@view('index.html')
def index(…):
?
Run Code Online (Sandbox Code Playgroud)
但是这个新奇的"注释"功能使得Python处于相反的方向:因为你只能对给定的函数进行一次注释,它完全打破了从各个部分组成解决方案的能力.如果你有两个库,每个都希望你代表他们注释相同的功能,那么,从我所看到的,你将完全陷入困境.