Search code examples
pythonpython-typingnonetype

None vs NoneType for type annotation


If a function can return None, shouldn't the type annotation use NoneType?

For example, shouldn't we use this:

from types import NoneType

def my_function(num: int) -> int | NoneType:

    if num > 0:
        return num

    return None

instead of:

def my_function(num: int) -> int | None:

    if num > 0:
        return num

    return None

?


Solution

  • No. types.NoneType was removed in Python 3. Attempting to import NoneType from types will produce an ImportError in Python 3, before Python 3.10. (For Python 3.10, types.NoneType was reintroduced; however, for the purposes of type hinting, types.NoneType and None are equivalent, and you should prefer the latter for conciseness.)

    In Python 3.10, int | None is the way to describe a return type that could possibly be None. However, for Python versions earlier than 3.10, this syntax is unsupported, so you should use Optional[int] instead.