Python Best Practices

Chapter 2 · Practice 3 of 5

Compare to None with is, and check types with isinstance

From Style, formatting and linting

Why it matters

Two comparisons look right and behave subtly wrong:

  • x == None calls the object's __eq__, which a class can override. PEP 8 says to compare singletons like None with is or is not.
  • type(x) == dict fails for subclasses such as OrderedDict. Use isinstance(x, dict), or better, collections.abc.Mapping when any mapping will do.

Also watch for truthiness: if not items: is the idiomatic empty check, but if not count: is also true when count is 0. When zero is a valid value, write if count is None:.

Example

Python
def total(prices: list[float] | None = None) -> float:
    if prices is None:
        prices = []
    return sum(prices)

if isinstance(config, Mapping):
    ...