sublimetext2 - Get different results in Sublime Text and terminal when I run python code? -
i learning core python , doing exercise:
4-9. given next assignments:
a = 10 b = 10 c = 100 d = 100 e = 10.0 f = 10.0
what output of each of next , why?
a b c d e f
when did in sublime text 2, pressed cmd + b build, got true.
a = 10 b = 10 c = 100 d = 100 e = 10.0 f = 10.0 print b print c d print e f output: true true true [finished in 0.0s] but when in terminal, got:
output: true true false # it's expect why results different?
i'm going assume know why integer values in a, b, c , d reused (they interned little integers).
the python bytecode compiler stores immutable literals (such floats) constants bytecode. when utilize same literal more 1 time in row, same constant reused. means e , f both assigned same bytecode constant; same float object used both , e f 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 utilize same index (0) load floating point object; constants construction contains one float object.
however, python interactive session compiles each statement separately; bytecode compiler doesn't chance re-use constant, , 2 distinct objects stored instead. time f = 10.0 compiled, e = 10.0 has been compiled , executed already, , codeobject assignment gone.
this why see difference between running script in 1 go (as sublime text build command does) , pasting code python interactive session.
python sublimetext2 read-eval-print-loop python-internals
No comments:
Post a Comment