Apr-28-2019, 07:07 AM
(This post was last modified: Apr-28-2019, 07:54 AM by Gribouillis.)
Nwb Wrote:That is only for -5 to 255 right. But if you assign an integer variable a value that isn't part of that range, then it creates a new object.This criticism only applies to literal constants in the interactive interpreter. It is not the assignment that creates the copy.
Python also doesn't point to the same integer object though it already exists
Var = 5000
Var2 = 5000
Var and Var2 are pointing to different objects according to the interpreter.
>>> x = 8000 >>> y = x >>> x is y TrueThe reason for the behavior you mentioned above is that in the interactive mode, each statement is compiled separately because it must be executed immediately. So python compiles the statement
Var = 5000
, which creates a int object and executes it. When it compiles the second statement Var2 = 5000
, it doesn't keep track of the previous constant 5000.This is different if you compile a function (or a whole file), for example
>>> def func(): ... var = 5000 ... var2 = 5000 ... print(var is var2) ... >>> func() TrueThis time the compiler can detect that the code uses the same constant twice because the statements in func's body are compiled together. All of this has nothing to do with the assignment operator.
>>> exec(""" ... var = 5000 ... var2 = 5000 ... print(var is var2) ... """) TrueAlso note that this is a very small issue, because the number of literal constants in code is usually small.