close

How to specify “nullable” return type with type hints

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to specify “nullable” return type with type hints in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to specify “nullable” return type with type hints?

  1. How to specify “nullable” return type with type hints?

    You could just use simillar to OR operator ( the vertical line | ):
    def get_some_date(some_argument: int=None) -> datetime | None: # rest of code

  2. specify “nullable” return type with type hints

    You could just use simillar to OR operator ( the vertical line | ):
    def get_some_date(some_argument: int=None) -> datetime | None: # rest of code

Method 1

You’re looking for Optional.

Since your return type can either be 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 on typing, Optional is shorthand for:

Optional[X] is equivalent to Union[X, 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 and not realize it’s meaning, you could always use Union:

from typing import Union

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

But I doubt this is a good idea, Optional is an indicative name and it does save a couple of keystrokes.

As pointed out in the comments by @Michael0x2a Union[T, None] is tranformed to Union[T, type(None)] so no need to use type here.

Visually these might differ but programatically, in both cases, the result is exactly the sameUnion[datetime.datetime, NoneType] will be the type stored in get_some_date.__annotations__*:

>>> from typing import get_type_hints
>>> print(get_type_hints(get_some_date))
{'return': typing.Union[datetime.datetime, NoneType],
 'some_argument': typing.Union[int, NoneType]}

*Use typing.get_type_hints to grab the objects’ __annotations__ attribute instead of accessing it directly.

Method 2

You could just use simillar to OR operator ( the vertical line | ):

def get_some_date(some_argument: int=None) -> datetime | None:
   # rest of code

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read