Skip to the solution
MediumDSA12 min read

What is string interning in Python?

468 views

The problem

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 ==; is works only by accident and the compiler warns about is with a literal

Code / implementation expected: Optional β€” demonstrating a run-time-built string that is equal but not identical, and fixing it with sys.intern.

  • str
  • interning

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWhich strings get interned, and sys.intern
PythonWhy interning helps: identity-first lookups and deduplication

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 89 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do you handle dates, times and time zones in Python?

Continue