Is there a Python equivalent of the C# null-coalescing operator?
In Python, you can use the or
operator as an equivalent to the C# ??
null-coalescing operator. The or
operator will return the first truthy value (the value that evaluates to True
), otherwise, it provides the second operand:
Note: Our trusty or
operator, providing backup plans since... well, probably not that long ago, but who's counting, right?
Unfortunately, in Python, or
considers any falsy value (0
, False
, []
, ""
etc.) as equivalent to None
. To specifically check against None
, leverage the :=
operator, also known as the walrus operator (cause it looks like a walrus, apparently):
Warning: Feed the walrus wisely, they can be grumpy!
Alternative Null-Coalescing Methods
When you're navigating through the dictionary jungle, Python's .get()
method is a handy machete. It tries to fetch a value from a dictionary, but if that key is as elusive as a chameleon, it provides a default:
Note to self: default
is slang for "keyless" in Python dictionary land.
Null-coalescing for Nested Dictionaries
Python's .get()
can be chained to handle nested dictionaries, ensuring you won't bang head on a TypeError
:
Note: Chains are not just for rappers anymore, programmers love them too!
Python's getattr()
can fetch attributes from objects, but beware of its dark side—it raises exceptions faster than your angry manager:
Looks like getattr()
also prefers camouflage
over neon
. Who knew?
Bored of the current Python null-coalescing situation? Always keep an eye on PEP 505—like season 100 of your favorite T.V. show, it could be coming... eventually.
Recognizing Pitfalls
The or
operator doesn't discriminate—it evaluates both operands. This can be a letdown when operand number two is as slow as a sloth or as unpredictable as an escaped python:
Wow, who thought or
could be so needy and demanding?
Be wary using reduce
and lambda
for null-coalescing, as they don't have manners to short circuit:
Reduce: Providing poor short circuiting performance since... well, let's just say it's been a while.
The {}
fallback, when used with .get()
, helps in hunting down nested dictionary keys without triggering traps (aka exceptions).
Pro Strats for Null-Coalescing
For multi-level attribute access, be a coding ninja and use recursion:
Well, neon
is snazzy too, I guess.
The defaultdict
can be your ever-reliable plan B, making sure a wandering key won't leave you empty-handed:
Good ol' defaultdict
, always there when your keys go AWOL.
Was this article helpful?