In Python 2.7, the behavior of string IDs can be puzzling. While strings are immutable, their IDs seem to change over time. This article explores the reasons behind this behavior.
Id Interning in Python
CPython does not intern all strings by default. However, strings that meet certain criteria may be interned using the sys.intern() function or the PyCode_New function's intern_string_constants() call. Internment ensures that multiple occurrences of the same string in the codebase use the same object.
Strings that qualify for interning include:
Changing IDs
If a string does not qualify for interning, its ID will continue to change. This is because Python is free to reuse memory locations for new strings, leading to different IDs for the same literal.
Interning and String Usage
The behavior of IDs depends on how the string is used:
Concatenating Strings
Concatenating strings also affects IDs. Strings concatenated within optimizer limits may lead to interned strings, resulting in the same ID for the concatenated string.
Conclusion
The ID of an immutable string in Python 2.7 is not always the same due to interning mechanisms and memory reuse. Understanding these factors helps clarify the apparent inconsistency in string IDs.
The above is the detailed content of Why Do Immutable String IDs Appear to Change in Python 2.7?. For more information, please follow other related articles on the PHP Chinese website!