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
if value.__bool__()
returns True
or if value.__len__()
returns an integer other than 0
, or if value
is neither None
or 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:
1 | + | from typing import Optional | |
2 | + | ||
3 | + | def foo_bar(value: Optional[str] = None): | |
4 | + | if value: |
Checking Optional variables against None
would be more explicit.
- | if value: |
+ | if value is not None: |
5 | + | ... |