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.
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
However, there are exceptions. Strings that meet the following criteria are interned and will maintain the same id():
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
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).
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.
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!