EDIT 2021:
There is a new package that is sort of a hack featuring exactly this functionality in Python. Here is the repo: https://github.com/paaksing/nullsafe-python
from nullsafe import undefined, _
value = _(variable).method()
assert value is undefined
assert not value
assert value == None
Works with AttributeError and KeyError aswell
dic = {}
assert _(dic)["nah"] is undefined
assert _(dic).nah is undefined
The wrapped object typings will remain effective.
-
No, there isn’t.
-
But to check for
None, you don’t writeif x:, you writeif x is None:. This is an important distinction –xevaluates toFalsefor quite a few values that are propably perfectly valid (most notably 0-equivalent numbers and empty collections), whereasx is Noneonly evaluates toTrueif the referencexpoints to the singleton objectNone. -
From personal experience, such an operator would be needed very rarely. Yes,
Noneis sometimes used to indicate no value. But somehow – maybe because idiomatic code returns null objects where sensible or throws exceptions to indicate critical failure – I only get anAttributeError: 'NoneType' object has no attribute '...'twice a month. -
I would argue that this might be a misfeature.
nullhas two meanings – “forgot to initialize” and “no data”. The first is an error and should throw an exception. The second case usually requires more elaborate handling than “let’s just not call this method”. When I ask the database/ORM for aUserProfile, it’s not there and I getnullinstead… do I want to silently skip the rest of the method? Or do I really want to (when in “library code”) throw an approriate exception (so “the user (code)” knows the user isn’t there and can react… or ignore it) or (when I’m coding a specific feature) show a sensible message (“That user doesn’t exist, you can’t add it to your friend list”) to the user?