You can use the function property __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'>}
Now we can do something to check it programatically:
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
Examples:
>>> 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
>>>
EDIT: To answer your comment, to check Union objects directly:
type(None) in obj.__args__
This would return True if None is there and False otherwise (assuming obj is a Union)