我想过滤 Union[..] 中任何参数为 None 的代码。识别 None 参数的最佳方法是什么?
我知道参数的顺序在 Union[] 中并不重要(来自输入 import Union),但是如何进行常见检查(可能是函数)来检测 None 参数。
from typing import Union
Union[T, None]
Run Code Online (Sandbox Code Playgroud)
您可以使用函数属性__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'>}
Run Code Online (Sandbox Code Playgroud)
现在我们可以做一些事情来以编程方式检查它:
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
Run Code Online (Sandbox Code Playgroud)
例子:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
编辑:要回答您的评论,请直接检查Union对象:
type(None) in obj.__args__
Run Code Online (Sandbox Code Playgroud)
True如果None存在则返回,False否则返回(假设obj是 a Union)