2
from inspect import signature
from typing import get_type_hints
def check_range(f):
def decorated(*args, **kwargs): #something should be modified here
counter=0
# use get_type_hints instead of __annotations__
annotations = get_type_hints(f)
# bind signature to arguments and get an
# ordered dictionary of the arguments
b = signature(f).bind(*args, **kwargs).arguments
for name, value in b.items():
if not isinstance(value, annotations[name]):
msg = 'Not the valid type'
raise ValueError(msg)
counter+=1
return f(*args, **kwargs) #something should be modified here
return decorated
@check_range
def foo(a: int, b: list, c: str):
print(a,b,c)
我之前问过另一个问题,它得到了很好的回答。但另一个不同的问题突然出现了......我怎么让它不互动空闲显示此:如何显示修饰器的原始参数
而是要说明这一点:
再次感谢您的帮助 – abccd
不客气@abccd。由于你正在执行一些类型检查,我想指出Python有一个* static *类型检查器,可以为你进行类型检查。这就是所谓的“mypy”,如果感兴趣的话可以查看一下。 –
我一定会考虑它的。并再次感谢:) – abccd