The is Operator's Unexpected Behavior with Non-Cached Integers
Question:
Within a function, the is operator returns True when comparing two integer literals outside the range of [-5, 256], but False when done outside the function. Why does this inconsistency occur?
Answer:
tl;dr:
The Python interpreter executes code blocks as units. Functions are single blocks, while interactive commands are separate blocks. Each block contains its own objects, including integers. Thus, integers declared within a function point to the same object, while those declared outside do not.
Elaboration:
-
Function:
- Code block is defined within the function.
- Literals within the block (e.g., 1000) are stored as a single object.
- is checks object identity, so a is b within the function returns True because a and b both point to the same object.
-
Interactive Commands:
- Each command is executed as a separate code block.
- Literals within each block are stored as separate objects.
- is checks object identity, and since the objects for literals are different, a is b returns False.
Additional Observations:
- This behavior holds true for non-integer literals (e.g., float literals).
- Python uses a dictionary to store constants within code objects, and checks for existing constants before adding new ones.
Caveats:
-
Chained Statements: When commands are chained (e.g., a = b = 1000), they are interpreted as a single code block, leading to True.
-
Module Level Execution: Module level execution (e.g., a = b = 1000) occurs within a single code block, resulting in True.
-
Mutable Objects: The inconsistency does not apply to mutable objects; a = b = [] will always yield False.
The above is the detailed content of Why Does the `is` Operator Behave Differently with Non-Cached Integers Inside and Outside Functions?. For more information, please follow other related articles on the PHP Chinese website!