Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any argument in Union[...] is None in python?

Tags:

python

union

I want to filter code where any of the argument in Union[..] is None. What is the best way to identify None arguments?

I know that the order of arguments does not matter in Union[](from typing import Union) but how do I a common check(possibly a function) to detect None arguments.

from typing import Union
Union[T, None]
like image 800
flames Avatar asked Oct 30 '25 16:10

flames


1 Answers

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)

like image 76
Ofer Sadan Avatar answered Nov 02 '25 05:11

Ofer Sadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!