日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 函数参数注解_python-如何使用函数注释来验证函数调用类...

發(fā)布時間:2023/12/9 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 函数参数注解_python-如何使用函数注释来验证函数调用类... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我最近才發(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。