我最近才發現有一種叫做函數注釋的東西,但是我不太確定如何使用它.這是我到目前為止的內容:
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?