Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxSeniorOccasionalTroubleshooting

Why can `a is b` sometimes return True for two separately written integer or string literals, and why is relying on this dangerous?

Answer

CPython caches small integers from -5 to 256 and interns many string literals that look like identifiers as a memory and speed optimization, so two separate literals can end up referencing the same cached object and `is` returns True by coincidence. This behavior is a CPython implementation detail, not a language guarantee: it can change between versions or contexts (for example, values built at runtime via concatenation or string formatting are usually not interned), so code should always use `==` for value comparisons and reserve `is` for identity checks against singletons like `None`.

Strong answer includes

  • small-int cache and string interning are implementation details
  • not guaranteed across versions or code paths
  • use == for values, is only for singleton identity

Practical example

Python example
x = 200; y = 200; x is y

is often True due to integer caching, but

Python example
x = 2000; y = 2000; x is y

is typically False because 2000 falls outside the cached range.

#cpython-internals#gotchas

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolsdis — Disassembler for Python bytecodePython Software Foundation · Bytecode execution model used to reason about interpreter performance