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

我最近才发现有一种叫做函数注释的东西,但是我不太确定如何使用它.这是我到目前为止的内容:

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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值