函数注释:PEP-3107
我遇到了一段演示 Python3 函数注释的代码片段。这个概念很简单,但我想不出为什么这些是在 Python3 中实现的,或者它们有什么好的用途。也许SO可以启发我?
它是如何工作的:
def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
... function body ...
参数后面冒号后面的都是一个“注解”,->
后面的信息是函数返回值的注解。
foo.func_annotations 会返回一个字典:
{'a': 'x',
'b': 11,
'c': list,
'return': 9}
提供这个有什么意义?
最佳答案
函数注释就是你对它们所做的。
它们可用于文档:
def kinetic_energy(mass: 'in kilograms', velocity: 'in meters per second'):
...
它们可用于前置条件检查:
def validate(func, locals):
for var, test in func.__annotations__.items():
value = locals[var]
msg = 'Var: {0}\tValue: {1}\tTest: {2.__name__}'.format(var, value, test)
assert test(value), msg
def is_int(x):
return isinstance(x, int)
def between(lo, hi):
def _between(x):
return lo <= x <= hi
return _between
def f(x: between(3, 10), y: is_int):
validate(f, locals())
print(x, y)
>>> f(0, 31.1)
Traceback (most recent call last):
...
AssertionError: Var: y Value: 31.1 Test: is_int
另见 http://www.python.org/dev/peps/pep-0362/一种实现类型检查的方法。
https://stackoverflow.com/questions/3038033/