Should you write "if x is not None" or "if not x is None" in Python? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

Should you write "if x is not None" or "if not x is None" in Python?

message-square
0

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 over if not x is None: (PEP 8 & E714):
    • Python provides is not as a dedicated binary identity operator (IS_OP with invert=1 in bytecode) rather than wrapping x is None in a prefix boolean not.
    • Linters (ruff, flake8, pycodestyle) flag if not x is None: with rule E714 (test for object identity should be 'is not') and auto-fix it to if x is not None:.
  • Zero performance difference (dis bytecode):
    • CPython compiles both x is not None and not x is None to the exact same bytecode instruction—choosing is not None is strictly about readability, intent clarity, and linter compliance.
  • Avoid if x: when 0, "", [], or False are valid values:
    • Never shortcut if x is not None: to truthiness (if x:) unless you want 0, 0.0, "", [], {}, and False treated identically to None. For example, timeout = 0 or items = [] passes if x is not None: (True) but fails if x: (False).
  • Always use is None / is not None instead of == None / != None (PEP 8 E711):
    • None is a singleton (NoneType). Using == or != invokes __eq__(), which can fail or raise ValueError on NumPy arrays and Pandas Series, whereas is / is not compares 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.