Basic Example
user_token: str | None = "abc123"
# 1. Recommended (PEP 8 compliant): Clear, idiomatic identity negation
if user_token is not None:
print(f"Token length: {len(user_token)}") # Output: Token length: 10
# 2. Discouraged by PEP 8 & linters (ruff E714 / flake8 E714): Harder to scan
if not user_token is None:
print("Works, but triggers linter warning E714")
Key Details & Edge Cases
- Why
if x is not None:is preferred overif not x is None:(PEP 8 & E714):- Python provides
is notas a dedicated binary identity operator (IS_OPwithinvert=1in bytecode) rather than wrappingx is Nonein a prefix booleannot. - Linters (
ruff,flake8,pycodestyle) flagif not x is None:with rule E714 (test for object identity should be 'is not') and auto-fix it toif x is not None:.
- Python provides
- Zero performance difference (
disbytecode):- CPython compiles both
x is not Noneandnot x is Noneto the exact same bytecode instruction—choosingis not Noneis strictly about readability, intent clarity, and linter compliance.
- CPython compiles both
- Avoid
if x:when0,"",[], orFalseare valid values:- Never shortcut
if x is not None:to truthiness (if x:) unless you want0,0.0,"",[],{}, andFalsetreated identically toNone. For example,timeout = 0oritems = []passesif x is not None:(True) but failsif x:(False).
- Never shortcut
- Always use
is None/is not Noneinstead of== None/!= None(PEP 8 E711):Noneis a singleton (NoneType). Using==or!=invokes__eq__(), which can fail or raiseValueErroron NumPy arrays and Pandas Series, whereasis/is notcompares object pointers directly in $O(1)$ time.
Comparison of None & Truthiness Checks in Python
| Expression | Evaluates True When x = 0 or ""? |
PEP 8 Compliant? | Linter Code | Best Used When |
|---|---|---|---|---|
if x is not None: (Recommended) |
Yes (True) |
Yes | Clean | Checking that an optional variable was provided, allowing 0, "", False, or []. |
if not x is None: |
Yes (True) |
No | E714 | Never—rewrite as if x is not None:. |
if x != None: |
Yes (True) |
No | E711 | Never—!= triggers __eq__() instead of singleton pointer identity. |
if x: (Truthiness) |
No (False) |
Yes | Clean | Checking that a value is both non-None and non-empty / non-zero. |
You must log in or register to comment.
