Home > Backend Development > Python Tutorial > Why Does Python\'s `id()` Change for Immutable Strings?

Why Does Python\'s `id()` Change for Immutable Strings?

Mary-Kate Olsen
Release: 2024-12-02 02:23:11
Original
962 people have browsed it

Why Does Python's `id()` Change for Immutable Strings?

Mutability and Object Identity in Python Strings

Python's immutability for strings implies that they cannot be altered once created. However, the object identity, represented by the id() function, can change for strings, leading to confusion.

id() Behavior for Strings

In general, the id() of strings changes every time it is called, even for the same string literal. This is because Python does not guarantee to intern all strings by default.

id('so')
140614155123888
id('so')
140614155123848
id('so')
140614155123808
Copy after login

However, there are exceptions. Strings that meet the following criteria are interned and will maintain the same id():

  • Constants stored in code objects
  • Strings containing only ASCII letters, digits, or underscores

Variable Scope and Interning

Assigning a string to a variable can influence its id() behavior. When a variable references a string, Python optimizes for performance by storing the string's value in memory once, using the interned version.

so = 'so'
id('so')  # Now references the same interned string as 'so'
140614155123728
Copy after login

Source of Interning Behavior

Python internally uses a function to intern strings called intern_string_constants(). This function is applied to strings that meet the criteria mentioned earlier (e.g., 'hello' in your example).

Interning and Optimization

Python's compiler and optimizers also play a role in interning. The code object factory function may intern any string that can be represented as a valid identifier (e.g., 'so' in your second example). Additionally, the peephole or AST optimizer can fold simple expressions involving constants, leading to interned results.

Conclusion

While Python's strings are immutable, their id() can change, depending on factors such as interning, variable scope, and optimizer behavior. Interning helps optimize memory usage and performance, and it can be valuable to understand its behavior to avoid potential confusion.

The above is the detailed content of Why Does Python\'s `id()` Change for Immutable Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template