Signature
import inspect
def foo(a, b, x='blah'):
pass
print(signature(foo))
# output:
(a, b, x='blah')
Annotations are documentation / comment for arguments while decorator transform the function. By itself, Python does not attach any particular meaning or significance to annotations.
def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
Combining Python Annotations and Decorators
https://code.tutsplus.com/tutorials/python-3-function-annotations--cms-25689:
def check_range(f):
def decorated(*args, **kwargs):
for name, range in f.__annotations__.items():
min_value, max_value = range
if not (min_value <= kwargs[name] <= max_value):
msg = 'argument {} is out of range [{} - {}]'
raise ValueError(msg.format(name, min_value, max_value))
return f(*args, **kwargs)
return decorated
@check_range
def foo(a: (0, 8), b: (5, 9), c: (10, 20)):
return a * b - c
print(foo(a=4, b=6, c=15) )
# 9
print(foo(a=4, b=6, c=105) )
# output :
# ValueError: argument c is out of range [10 - 20]
A big bonus Here ! :
def countdown(n:int):
for i in range(n):
print(i)
countdown(3.2)
# output :
# TypeError: 'float' object cannot be interpreted as an integer
留言
張貼留言