From the documentation - Union Type:
A union object holds the value of the |
(bitwise or) operation on multiple type objects. These types are intended primarily for type annotations. The union type expression enables cleaner type hinting syntax compared to typing.Union
.
This use of |
was added in Python 3.10. Hence the proper way to represent more than one return data type is:
def foo(client_id: str) -> list | bool:
For earlier versions, use typing.Union
:
from typing import Union
def foo(client_id: str) -> Union[list, bool]:
But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."
>>> def foo(a: str) -> list:
... return "Works"
...
>>> foo(1)
'Works'
As you can see I am passing an int value and returning a str. However the __annotations__
will be set to the respective values.
>>> foo.__annotations__
{'return': <class 'list'>, 'a': <class 'str'>}
Please go through PEP 483 for more about Type hints. Also see What are type hints in Python 3.5??
Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.
Best Answer
You're looking for
Optional
.Since your return type can either be
datetime
(as returned fromdatetime.utcnow()
) orNone
you should useOptional[datetime]
:From the documentation on typing,
Optional
is shorthand for:where
Union[X, Y]
means a value of typeX
orY
.If you want to be explicit due to concerns that others might stumble on
Optional
and not realize it's meaning, you could always useUnion
: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 toUnion[T, type(None)]
so no need to usetype
here.Visually these might differ but programatically, in both cases, the result is exactly the same;
Union[datetime.datetime, NoneType]
will be the type stored inget_some_date.__annotations__
*:*Use
typing.get_type_hints
to grab the objects'__annotations__
attribute instead of accessing it directly.