Python Glossary Русский

Python 3.0+sysfunction

sys.intern()

strings

Interns a string — it guarantees that identical strings share one object in memory. It speeds up comparison with 'is'.

Syntax

sys.intern(string: str) -> str

The real win is memory when the same string occurs thousands of times (keys parsed from a file, repeated tokens), not speed in general: plain == already starts with an identity check. You must keep a reference to the returned string yourself — interned strings are not immortal and die with the last reference. Do not turn this into a habit of comparing strings with is: CPython interns short literals on its own, so such code looks fine in toy examples and breaks on strings built at runtime.

Examples

import sys
a = sys.intern('hello')
b = sys.intern('hello')
print(a is b)  # → True
c = 'hel' + 'lo'
print(sys.intern(c) is a)  # → True
words = [sys.intern(w) for w in ['apple', 'banana', 'apple']]
print(words[0] is words[2])  # → True
print(type(sys.intern('x')))  # → <class 'str'>

See also

Open in the full glossarydocs.python.orgReport an inaccuracy