Apr-28-2024, 08:55 AM
(This post was last modified: Apr-28-2024, 08:55 AM by Gribouillis.)
(Apr-28-2024, 07:42 AM)akbarza Wrote: but this is inconsistence with result of running line 22 of the above code.It can be explained very easily by considering the bytecode generated by Python. Consider the following example
can explain to me the reason of this?
>>> def func(): ... x = 257 ... y = 257 ... return x is y ... >>> func() True >>> import dis >>> dis.dis(func) 2 0 LOAD_CONST 1 (257) 2 STORE_FAST 0 (x) 3 4 LOAD_CONST 1 (257) 6 STORE_FAST 1 (y) 4 8 LOAD_FAST 0 (x) 10 LOAD_FAST 1 (y) 12 IS_OP 0 14 RETURN_VALUE >>>In this code, the assignements
x = 257
and y = 257
occur in the body of the same function. When Python compiles this into bytecode, it allocates a single space in memory to store the literal constant 257 which appears twice in the body of the function. When executing the assignment statements, it simply points the variables x and y to the position where this memory was allocated. Hence x and y have the same memory address and x is y
returns True.On the other hand, if you run interactively
>>> x = 257 >>> y = 257then every statement is compiled separately into bytecode when you hit the return key. Each time, Python will allocate a new space in memory to store the constant 257, hence x and y will point to two different memory addresses.
The result of the compilation of Python code is a «code object». The code object contains the bytecode and also the literal constants that appear in the code. When your script is compiled, a single code object is created, hence several occurrences of the same constant can be shared. On the other hand, when two statements are executed interactively, two code objects are created and they cannot share their constants.
« We can solve any problem by introducing an extra level of indirection »