Explain Codes LogoExplain Codes Logo

Is there shorthand for returning a default value if None in Python?

python
prompt-engineering
best-practices
falsy-values
Nikita BarsukovbyNikita Barsukov·Feb 25, 2025
TLDR

Saving a spaceship from Noneish situations? Use Python's or operator to supply a life-saving default value when facing possible None values.

safety_net = variable or default_value

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.

safety_net = variable if variable is not None else default_value

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.

# Handle None faster than I chug my morning coffee database_field = db_value or default_value

None's bag of tricks

Falsy values, stand down!

The or operator evaluates left-to-right, squashing the first truthy value it finds:

- `None or default` => default - `0 or default` => default - `False or default` => default - `'a' or default` => 'a'

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.