Checking Optional variables against
None would be more explicit.
A part of the Zen of Python is implicit is better than implicit. Compare these two functions:
Which more explicitly communicates the intent of the code to the developer reading it? Which is more permissive of unexpected falsey inputs were passed inadvertently passed to the function?
Testing an object's truthiness via
if value evaluates to
True or if
value.__len__() returns an integer other than
0, or if
value is neither
False. That's a lot of things a developer must to consider when building a mental model of the code.
On the other hand, explicitly checking
if value is not None removes those branches of thought entirely from the mental model a developer has to build when reading and understanding the code.
If our GitHub code review bot spots this issue in your pull request it gives this advice:
Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code
compare-optional-against-none in your pyproject.toml file.