Result of Weird id on CPython IntObject

I write three lines of the same code and get different results, firstly, I run it in one interactive shell:

>>> a = 10000
>>> b = 10000
>>> a is b
False

>>> a = 10000; b = 10000; a is b
True

Then I have one Python file containing:

a = 10000
b = 10000
print a is b

I run it and get True

My Python environment:

Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

What's going on here? Everyone is talking about compilation, does anyone know how the interactive shell compiles and runs these lines of code?

+4
source share
4 answers

, True. , , Python , -, "" , . , *

, - , dis, - , , .

  2           0 LOAD_CONST               1 (10000)
              3 STORE_FAST               0 (a)
              6 LOAD_CONST               1 (10000)
              9 STORE_FAST               1 (b)
             12 LOAD_FAST                0 (a)
             15 LOAD_FAST                1 (b)
             18 COMPARE_OP               8 (is)
             21 RETURN_VALUE

:

def func():
    a = 10000; b = 10000; return a is b
from dis import dis
dis(func)

, LOAD_CONST . func.__code__.co_consts, . 1 int 10000.

, a = 10000; b = 10000; a is b, compile() :

  1           0 LOAD_CONST               0 (10000)
              3 STORE_NAME               0 (a)
              6 LOAD_CONST               0 (10000)
              9 STORE_NAME               1 (b)
             12 LOAD_NAME                0 (a)
             15 LOAD_NAME                1 (b)
             18 COMPARE_OP               8 (is)
             21 POP_TOP
             22 LOAD_CONST               1 (None)
             25 RETURN_VALUE

, /const, NAME vs FAST POP_TOP on. , , int.

* , IPython, a is b False.

+3

, . a = 10000, b = 10000, () .

, a b .

. , ..

>> a = 256; b = 256; a is b
True

>> a = 256; b = 256; a + 1 is b + 1
False

Peeon peephole (. https://github.com/python/cpython/blob/master/Python/peephole.c).

+1

python, . "" , . , "is", python "a" "b" . : = 1 = 1 a - b True , python ,

0

I just realized that actually those 10000 that have the same identifier are in the compiled code object:

>>> code = compile("a = 10000; b = 10000; a is b", "<string>", "exec")
>>> code.co_consts
(10000, None)

The compiler performs some optimization, and 10000 is created only once, because 10000 is unchanged :)

0
source

All Articles