David Y.
—FastAPI allows developers to set default values for query parameters. It also allows parameters to be declared as optional. But what is the difference between an optional parameter and a parameter that has None
as its default value? Consider the following code:
@app.get("/example-route/") async def example_route(p1: str = None, p2: str | None = None): return {"p1": p1, "p2": p2}
What is the difference between p1
and p2
? Is one preferable to the other?
The only difference between p1
and p2
is that the latter uses a more complex type hint. Type hints are an optional Python syntax feature that can be used to indicate what data type a given function parameter expects. Python is a dynamically typed language, so these type hints are not enforced as they might be in a statically typed language like C or Java – they merely act as a guide for developers and an aid for tooling such as auto-completion in code editors.
In the code above, we can see that p1
is expected to be a string (str
), whereas p2
is expected to be either a string or None
. However, because Python does not enforce type hints, we can set p1
to None
, which is not a value of type str
. We can also set p2
to None
, but its type hint includes this possibility, making it the more accurate of the two. This could be useful for editors and other tooling that interacts with our code, as well as for other developers. Therefore, this approach is preferable in most circumstances, but not strictly necessary for our code to function.
Note that the type hint str | None
can also be written as Optional[None]
or Union[str, None]
if these classes are imported from the built-in typing module.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.