Is there shorthand for returning a default value if None in Python?
Saving a spaceship from None
ish situations? Use Python's or
operator to supply a life-saving default value when facing possible None
values.
In layman's terms, if variable
turns out to be None
or falsy, safety_net
ensures you don't fall by grabbing default_value
.
While this method suits most scenarios, be aware that any falsy value, not just None
, will switch on the safety_net. How democratic!
For a None, and nothing but a None
In situations where you need a more rigorous check, specifically for None
, the ternary conditional won't let any other falsy value (looking at you, 0
!) distract it.
KeyUp, Space, Down, Repeat! This one-liner will persist till it finds None
, ignoring other tricky falsy values.
None, be gone, especially when database is on
For database operations, settings configurations, or burning the midnight oil before a project deadline, None
is the last thing you want. In such cases, find solace with our shorthand friend, the or
operator.
None's bag of tricks
Falsy values, stand down!
The or
operator evaluates left-to-right, squashing the first truthy value it finds:
So remember, kids, the order of evaluation in or
is a sequence, not a chow line.
Ternary: a scalpel of precision
Want None
and only None
to trigger the default? Ternary operator to the rescue! It's the surgeon of the operation theatre, making precise cuts to keep falsy values intact, while surgically removing None
.
Mindful tips for mindful Pythonistas
or
isn't synonym for shellfish 🦪
Python doesn't have a buffet of operators like C#'s ??
, and or
isn't shellfish, it just can't tell the difference between None
and other falsy values.
Hide and seek with exceptions
With or
, you might create a hide-n-seek champion with exceptions, covering them up with happy defaults. When you need None
values to feel special and raise exceptions, call for our good old friend, the ternary operator.
Was this article helpful?