Why does `is` sometimes work on strings?
CPython interns short string literals that look like identifiers, so two of them share one object and is happens to be True. Build the same text at runtime and it is False. It is an optimisation, not a guarantee — compare strings with ==, and keep is for None.
Overview
What interning is
CPython keeps a table of strings and reuses the entry rather than allocating a second identical object. Identifiers, and literals in compiled code that look like identifiers, go in it automatically. The payoff is real: comparing interned strings can short-circuit on a pointer comparison, and attribute lookup does this constantly.
Immutability is what makes it legal. Sharing one object between unrelated pieces of code would be a disaster if either could modify it.
Step through it
What to watch
- Both rows hold the same text; only how it was built differs.
==isTruein every frame.isis not.- Behaviour differs between the REPL and a script — which is the point.
Say this out loud
"That's interning - CPython reuses one object for short literals. It's an implementation detail, so I compare with == and only use `is` for None."