PROGRAMMING IN PYTHON
According python documentation, typing.Optional
is a practical way of indicating that an object can be None
. It’s a concise and elegant way to express this concept, but is it also very clear?
Let me rephrase this question: when you see the word “optional” in a Python context, what do you think it means? Imagine that you see an argument called x
that has the type of Optional(int)
. He int
part is pretty clear since it most likely indicates an integer, but what does it mean Optional
mean? What is your first thought?
Let’s consider the following two options:
- I do not have to provide a value of
x
because it is optional. x
the value can be anyint
eitherNone
.
If you know Python type hints well enough, you will know that option 2 is correct. But when you don’t… Maybe I’m wrong, but I can’t imagine any person who doesn’t know Python choosing option 2. It’s option 1 that seems to make the most sense. When I see information that something is optional, I think that… well, that it is optional…
This problem leads to frequent misuse of the typing.Optional
guy. This article aims to shed light on this misuse and guide you towards the correct understanding of this type.
These three types of suggestions are equivalent:
from typing import Optional, Unionx: Union(str, None)
x: Optional(str)
x: str | None
Each of them transmits the same information: that x
can be a string or None
. While it is perfectly valid, the first (Union(str, None)
) represents the early stages of type hinting in Python: it was the initial approach, but is not necessarily the preferred method today. So, Optional
was added to the typing
module, which provides a more concise and direct way to express this concept. According he mypy
documentation:
You can use the
Optional
type modifier to define a type variant that allowsNone
asOptional(int)
(Optional(X)
is the preferred abbreviation forUnion(X, None)
).