What's with the Integer Cache Maintained by the Interpreter?
Python optimizes identical literals when compiling them into the same code object, resulting in objects having the same identity. Typically, integers within the range [-5, 256] are cached, but this does not guarantee that all integers within this range will have the same identity.
In the example code you provided, when you execute each line separately in the Python shell:
>>> a = 1 >>> b = 1 >>> a is b True
the code is parsed and compiled separately for each line. However, when you run the same code together in a file:
>>> a = 257; b = 257; a is b True
the compiler can optimize the literals. During the compilation process, the AST is transformed into bytecode, and the compiler analyzes the usage of literals to avoid duplicating them. This results in a single constant for the integer 257 in the compiled code.
This optimization is not limited to integers but also applies to other literals such as floats. However, it does not work for more complex literals like tuples, where the literals inside the tuple are optimized separately.
The reason why you observed two PyInt_Objects being created is likely due to the parser's approach to converting literals to integers. The parser uses a function that converts the literal to an integer value and then calls PyLong_FromString to create the integer object. This approach avoids rewriting the conversion code and allows for easy extension.
However, the final optimization to ensure that equal constants use the same object occurs during bytecode compilation, not during AST transformation. Specifically, the compiler_add_o function is responsible for storing constants in a dictionary object, resulting in identical constants falling into the same slot and being represented by a single constant in the final bytecode.
The above is the detailed content of Why Does Python Cache Some Integers But Not Others?. For more information, please follow other related articles on the PHP Chinese website!