Question presented to candidate:
"Sometimes two equal strings in Python are the same object and sometimes they are not. What is string interning, which strings does CPython intern on its own, when would you call sys.intern yourself, and why is comparing strings with is still a mistake?"
What a strong answer should cover:
- Interning means keeping one canonical object per distinct string value in an interpreter-wide table and reusing it, so equal interned strings are also identical (
is) - CPython interns automatically: identifiers (variable, function, attribute and keyword-argument names), string constants that look like identifiers (ASCII letters, digits, underscore), the empty string, and attribute names passed to
setattr/getattr; it does not intern strings built at run time, read from files or with spaces/punctuation/non-ASCII - Why: dict lookups compare by identity before calling
__eq__and strings cache their hash, so interned keys (namespaces,__dict__, keyword arguments) are found with a pointer comparison; it also saves memory for repeated values sys.intern(s)returns the canonical copy; useful when the same few strings are repeated a huge number of times (parsed logs, CSV columns, tokens), with the cost of one hash lookup per call- It is a CPython implementation detail: compare strings with
==;isworks only by accident and the compiler warns aboutiswith a literal
Code / implementation expected: Optional β demonstrating a run-time-built string that is equal but not identical, and fixing it with sys.intern.