Why Does '20000 Is 20000' Result In True?
Solution 1:
The Python interpreter sees you are re-using a immutable object, so it doesn't bother to create two:
>>> import dis
>>> dis.dis(compile('20000 is 20000', '', 'exec'))
1 0 LOAD_CONST 0 (20000)
3 LOAD_CONST 0 (20000)
6 COMPARE_OP 8 (is)
9 POP_TOP
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
Note the two LOAD_CONST
opcodes, they both load the constant at index 0:
>>> compile('20000 is 20000', '', 'exec').co_consts
(20000, None)
In the interactive interpreter Python is limited to having to compile each (simple or compound) statement you enter separately, so it can't reuse these constants across different statements.
But within a function object it certainly would only create one such integer object, even if you used the same int literal more than once. The same applies to any code run at the module level (so outside of functions or class definitions); those all end up in the same code object constants too.
Solution 2:
Python stores objects in memory to make things more efficient. It only needs to assign one block of memory to 20000
, and so both references point to the same block of memory, resulting in True
.
Post a Comment for "Why Does '20000 Is 20000' Result In True?"