如何检查Union [...]中的任何参数在python中是否为None?

时间:2019-10-01 19:09:54

标签: python union

我要过滤在Union [..]中任何参数为None的代码。识别无参数的最佳方法是什么?

我知道在Union []中参数的顺序无关紧要(通过键入import Union来实现),但是如何进行通用检查(可能是一个函数)来检测None参数。

from typing import Union
Union[T, None]

1 个答案:

答案 0 :(得分:3)

您可以使用函数属性__annotations__

def my_func(a: Union[int, None], b: int, c: str):
    print(a,b,c)

print(my_func.__annotations__) # {'a': typing.Union[int, NoneType], 'b': <class 'int'>, 'c': <class 'str'>}

现在我们可以做一些编程检查:

from typing import _GenericAlias

def check_if_func_accepts_none(func):
    for key in func.__annotations__:
        if isinstance(func.__annotations__[key], type(None)):
            return True
        elif isinstance(func.__annotations__[key], _GenericAlias) and type(None) in func.__annotations__[key].__args__:
            return True
    return False

示例:

>>> def b(a:int, b:None):
...     print('hi')
...
>>> def c(x:Union[None,str], y:int):
...     print('hi')
...
>>> def d(z: int, s:str):
...     print('hi')
...
>>> check_if_func_accepts_none(b)
True
>>> check_if_func_accepts_none(c)
True
>>> check_if_func_accepts_none(d)
False
>>>

编辑:要回答您的评论,请直接检查Union个对象:

type(None) in obj.__args__

如果存在True,则返回None,否则返回False(假设objUnion