if A vs if A is not None
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
if A: and if A is not None: answer different questions in Python. The first checks truthiness. The second checks only whether the value is the singleton None. Using the wrong one is a common cause of bugs when 0, "", or [] are valid inputs.
Truthiness and if A:
Python treats many values as false in conditionals:
- '
None' - '
False' - '
0' - '
0.0' - '
""' - '
[]' - '
{}'
Example:
This is the right test when your real intention is "does this value contain useful content."
if A is not None: Means Something Narrower
None is a special marker for "no value." A None check ignores general truthiness and asks only whether the variable is missing.
Here, 0, "", and [] all pass the check because they are real values, even though they are falsy.
The Classic Bug
Consider an optional numeric argument:
This prints "default limit", which is wrong if 0 is a meaningful explicit value.
Correct version:
Now the semantics are correct.
When if A: Is Better
Use if A: when emptiness itself should count as false.
That is a good fit because an empty list really means there is nothing to do.
Strings are another common case:
If blank input should be treated the same as missing input, if name: is the cleaner choice.
Why is not None Beats != None
When checking for None, use identity comparison:
This is better than value != None because None is a singleton and identity expresses the real intent directly. It also avoids odd behavior from custom equality implementations.
Custom Classes Can Change the Result of if A:
Objects can define __bool__ or __len__, which means even custom instances can be falsy.
That is another reason the two conditions are not style variants. One respects truthiness rules. The other checks only for None.
A Practical Rule
Ask yourself:
- Should all falsy values be rejected.
- Or should only the missing marker
Nonebe rejected.
If the first answer is correct, use if A:.
If the second answer is correct, use if A is not None:.
That decision is about data meaning, not about which syntax looks nicer.
Common Pitfalls
- Using
if A:when0or""are valid values. - Using
if A is not None:when empty containers should also count as missing. - Comparing to
Nonewith==instead ofis. - Forgetting that custom objects can override truthiness.
- Choosing the shorter form without thinking about semantics.
Summary
- '
if A:checks truthiness.' - '
if A is not None:checks only forNone.' - Use
if A:when empty and zero-like values should count as false. - Use
if A is not None:when falsy values can still be valid input. - The correct condition depends on what the value means in your program.

