我最近才发现有一种叫做函数注释的东西,但是我不太确定如何使用它.这是我到目前为止的内容:
def check_type(f):
def decorated(*args, **kwargs):
counter=0
for arg, type in zip(args, f.__annotations__.items()):
if not isinstance(arg, type[1]):
msg = 'Not the valid type'
raise ValueError(msg)
counter+=1
return f(*args, **kwargs)
return decorated
@check_type
def foo(a: int, b: list, c: str): #a must be int, b must be list, c must be str
print(a,b,c)
foo(12, [1,2], '12') #This works
foo(12, 12, 12) #This raises a value error just as I wanted to
foo(a=12, b=12, c=12) #But this works too:(
如您所见,我正在尝试使用批注和装饰器检查a,b和c的类型,如果类型不正确,则会引发ValueError.当我在调用时不使用关键字参数时,效果很好.但是,如果我使用关键字参数,则不会检查类型.我正在尝试使其正常运行,但是我没有运气.
我的代码不支持关键字参数.因为我没有任何可以检查的内容.我也不知道如何检查它.这是我需要帮助的地方.
我也是这样做的:
def check_type(f):
def decorated(*args, **kwargs):
for name, type in f.__annotations__.items():
if not isinstance(kwargs[name], type):
msg = 'Not the valid type'
raise ValueError(msg)
return f(*args, **kwargs)
return decorated
#But now they have to be assigned using keyword args
#so only foo(a=3,b=[],c='a') works foo(3,[],'a') results in a keyerror
#How can I combine them?