我要过滤在Union [..]中任何参数为None的代码。识别无参数的最佳方法是什么?
我知道在Union []中参数的顺序无关紧要(通过键入import Union来实现),但是如何进行通用检查(可能是一个函数)来检测None参数。
from typing import Union
Union[T, None]
答案 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
(假设obj
是Union
)