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
?
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.