python 函数参数注解_python-如何使用函数注释来验证函数调用类...
我最近才發(fā)現(xiàn)有一種叫做函數(shù)注釋的東西,但是我不太確定如何使用它.這是我到目前為止的內(nèi)容:
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的類型,如果類型不正確,則會引發(fā)ValueError.當(dāng)我在調(diào)用時不使用關(guān)鍵字參數(shù)時,效果很好.但是,如果我使用關(guān)鍵字參數(shù),則不會檢查類型.我正在嘗試使其正常運(yùn)行,但是我沒有運(yùn)氣.
我的代碼不支持關(guān)鍵字參數(shù).因?yàn)槲覜]有任何可以檢查的內(nèi)容.我也不知道如何檢查它.這是我需要幫助的地方.
我也是這樣做的:
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?
總結(jié)
以上是生活随笔為你收集整理的python 函数参数注解_python-如何使用函数注释来验证函数调用类...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SVM多分类问题
- 下一篇: python理论知识选择题_Python