-1

Is there a way to create a brand new object with canonic operations ? I am a bit confused by the example below :

x = 1
y = int.__new__(int, 1)
print x is y

>> True

EDIT :

“is” operator behaves unexpectedly with integers enlights the example above, but doesn't answer the question about the existence of a canonic way to create two different int objects. In the end, it just helps to understand that writing x = 256; y = 256 is not a solution, which is not what I was looking for.

Community
  • 1
  • 1
Thrastylon
  • 853
  • 7
  • 20
  • 1
    The point is that x and y are references that are pointing to the same thing – PyNEwbie May 24 '16 at 13:55
  • I took your code a step further and assigned 2 to x and learned that x is not y any longer. This concept about references is critical to understanding some potential gotcha's in Python – PyNEwbie May 24 '16 at 13:58
  • I'm confused by the example as well... the `x is y` bit is (I think) a CPython specific optimization and demonstrates it _not_ creating a brand new object. What was the example _supposed_ to show? – mgilson May 24 '16 at 14:00
  • 1
    @PyNEwbie you need to read up on immutable vs mutable - integers are the former. See http://nedbatchelder.com/text/names.html – jonrsharpe May 24 '16 at 14:04
  • @jonrsharpe Great link – PyNEwbie May 24 '16 at 14:14

1 Answers1

4

Is there a way to create a brand new object with canonic operations ?

For the object 1? No. For other integers, yes. In python, objects are references that point to an instance of an object. An int in python is an object that exists on the heap, and all python variables that are 1 are really object references that point to a heap object (which stores the int object). In python, all numbers between -5 and 256 have dedicated int objects so that the references to them are always equal.

In Python's documentation:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

For more clarification, see this SO post, that really all types in python are value types.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56