Explicitly compare Optional variables against None

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:

code-review-doctorbotsuggested changes just now
helpers.py
1
+
from typing import Optional
2
+
	
3
+
def foo_bar(value: Optional[str] = None):
4
+
    if value:
Suggested changes
-
    if value:
+
    if value is not None:
Commit suggestion

Checking Optional variables against None would be more explicit.

Read more
5
+
        ...
Update helpers.py
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

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.

Read more about configuring Code Review Doctor.