Chapter 2 · Practice 3 of 5
Compare to None with is, and check types with isinstance
Why it matters
Two comparisons look right and behave subtly wrong:
x == Nonecalls the object's__eq__, which a class can override. PEP 8 says to compare singletons likeNonewithisoris not.type(x) == dictfails for subclasses such asOrderedDict. Useisinstance(x, dict), or better,collections.abc.Mappingwhen 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
def total(prices: list[float] | None = None) -> float:
if prices is None:
prices = []
return sum(prices)
if isinstance(config, Mapping):
...