liyuhao
liyuhao

Reputation: 375

Get different results in Sublime Text and terminal when I run python code?

I am learning Core Python and doing an exercise:

4-9. Given the following assignments:

a = 10
b = 10
c = 100
d = 100
e = 10.0
f = 10.0

What is the output of each of the following and why?

a is b
c is d
e is f

when I did it in sublime text 2, pressed cmd + B to build, I got all True.

a = 10
b = 10
c = 100
d = 100
e = 10.0
f = 10.0
print a is b
print c is d
print e is f

Output:  
True
True
True
[Finished in 0.0s]

But when I do it in terminal, I got:

Output:  
True
True
False # It's what I expect

Why the results are different?

Upvotes: 0

Views: 161

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121276

I'm going to assume you already know why the integer values in a, b, c and d are reused (they are interned like all small integers).

The Python bytecode compiler stores immutable literals (such as floats) as constants with the bytecode. When you use the same literal more than once in a row, the same constant is reused. That means that e and f are both assigned the same bytecode constant; the same float object is used for both and e is f is True:

>>> import dis
>>> assignment = compile('''\
... e = 10.0
... f = 10.0
... ''', '<stdin>', 'exec')
>>> dis.dis(assignment)
  1           0 LOAD_CONST               0 (10.0)
              3 STORE_NAME               0 (e)

  2           6 LOAD_CONST               0 (10.0)
              9 STORE_NAME               1 (f)
             12 LOAD_CONST               1 (None)
             15 RETURN_VALUE        
>>> assignment.co_consts
(10.0, None)

Note how both LOAD_CONST instructions use the same index (0) to load the floating point object; the constants structure contains just the one float object.

However, the Python interactive session compiles each statement separately; the bytecode compiler doesn't get a chance to re-use the constant, and two distinct objects are stored instead. By the time f = 10.0 is compiled, e = 10.0 has been compiled and executed already, and the codeobject for that assignment is already gone.

This is why you see a difference between running the script in one go (as the Sublime Text Build command does) and pasting the code into the Python interactive session.

Upvotes: 1

Related Questions