exfizik exfizik - 2 months ago 13
Python Question

How to specify "nullable" return type with type hints

Suppose I have a function:

def get_some_date(some_argument: int=None) -> %datetime_or_None%:
if some_argument is not None and some_argument == 1:
return datetime.utcnow()
else:
return None


How do I specify the return type for something that can be
None
?

Jim Jim
Answer

Since your return type can be either datetime (as returned from datetime.utcnow) or None you should use Optional[datetime]:

from typing import Optional

def get_some_date(some_argument: int=None) -> Optional[datetime]:
    # as defined

From the documentation, Optional is shorthand for:

Optional[X] is equivalent to Union[X, type(None)].

where Union[X, Y] means a value of type X or Y.


If you want to be explicit due to concerns that others might stumble on Optional you can always use Union:

from typing import Union

def get_some_date(some_argument: int=None) -> Union[datetime, type(None)]:

In either case the result is exactly the same; Union[datetime, NoneType] will be stored in get_some_date.__annotations__['return'].