Home >Backend Development >Python Tutorial >Why Do Immutable String IDs Appear to Change in Python 2.7?

Why Do Immutable String IDs Appear to Change in Python 2.7?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 16:22:18311browse

Why Do Immutable String IDs Appear to Change in Python 2.7?

Why Does the ID of an Immutable String Change?

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:

  • Constants stored in code objects
  • Strings containing only ASCII letters, digits, or underscores
  • Strings that are assigned to both an identifier and its value (e.g., so = 'so')

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:

  • Without a Variable Reference: If you call id('so') multiple times without assigning it to a variable, the ID may change because the interned string object is discarded.
  • With a Variable Reference: If you assign a string to a variable (e.g., so = 'so'), the ID will remain the same because the interned string is bound to the variable.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn