Python Forum
About integer objects vs integer values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
About integer objects vs integer values
#12
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.

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.
This criticism only applies to literal constants in the interactive interpreter. It is not the assignment that creates the copy.
>>> x = 8000
>>> y = x
>>> x is y
True
The 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()
True
This 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)
... """)
True
Also note that this is a very small issue, because the number of literal constants in code is usually small.
Reply


Messages In This Thread
About integer objects vs integer values - by Nwb - Apr-25-2019, 04:55 AM
RE: About integer objects vs integer values - by Gribouillis - Apr-28-2019, 07:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Does the integer implementation matter? ichabod801 2 1,846 Oct-22-2019, 03:26 PM
Last Post: snippsat
  integer bases Skaperen 7 4,724 Nov-24-2017, 09:46 AM
Last Post: heiner55
  multiplying integer to decimal ArnabRoyBatman 8 12,694 Jun-20-2017, 04:49 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020