Understanding the Changing ID of Immutable Strings in Python
In Python, immutable string objects typically have changing IDs due to factors such as string interning, memory location reuse, and code optimization. While immutability suggests a constant ID, the following behavior has been observed:
Original Observation:
id('so') # Changes on every call
Changing IDs:
This behavior is caused by the lack of guaranteed string interning in CPython. Python does not always intern strings, so repeated calls to id('so') may yield different IDs.
Memory Location Reuse:
Python can reuse memory locations for new string objects, leading to occasional ID matches even for different strings. This is unpredictable and depends on memory usage.
Code Optimization:
Python optimizers may fold constant expressions (e.g., 'foo' 'bar') at compile time, storing the resulting string in a single memory location. This leads to consistent IDs for these expressions.
Exception:
Constant strings that use ASCII letters, digits, or underscores are interned by the Python compiler. Therefore, subsequent literals with the same characters will reuse the same interned string object, resulting in consistent IDs.
Additional Observations:
The above is the detailed content of Why Do Immutable Python Strings Seem to Have Changing IDs?. For more information, please follow other related articles on the PHP Chinese website!