python中union,在Python 3.6中运行时根据Union类型检查变量

博客探讨了如何在Python中创建一个函数装饰器,该装饰器利用3.6及更高版本的类型提示来验证传入字典参数的类型。作者遇到了问题,即无法在运行时针对`Union`类型的参数进行实例检查。解决方案是通过访问`Union`类型的`__args__`属性来获取可能的类型,并用它来进行实例检查。虽然`__args__`不是官方文档的一部分,但它是实现细节的一个有效途径。
摘要由CSDN通过智能技术生成

I'm trying to write a function decorator that uses Python 3.6 type hints to check that a dictionary of arguments respects the type hints and if not raise an error with a clear description of the problem, to be used for HTTP APIs.

The problem is that when the function has a parameter using the Union type I can't check a variable against it at runtime.

For example, I have this function

from typing import Union

def bark(myname: str, descr: Union[int, str], mynum: int = 3) -> str:

return descr + myname * mynum

I can do:

isinstance('Arnold', bark.__annotations__['myname'])

But not:

isinstance(3, bark.__annotations__['descr'])

Because Union cannot be used with isinstance or issubclass.

I couldn't find a way to check it using the type object.

I tried to implement the check by myself but while bark.__annotations__['descr'] is shown as typing.Union[int, str] in the REPL I can't access the list of the types at runtime, if not using the ugly hack of examining bark.__annotations__['descr'].__repr__().

Is there a proper way to access this information? Or is it deliberately intended to not be easily accessible at runtime?

解决方案

You could use the __args__ attribute of Union which holds a tuple of the "possible contents:

>>> from typing import Union

>>> x = Union[int, str]

>>> x.__args__

(int, str)

>>> isinstance(3, x.__args__)

True

>>> isinstance('a', x.__args__)

True

The __args__ argument is not documented so it could be considered "messing with implementation details" but it seems like a better way than parsing the repr.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值