Is behavior of += intentional for int?
steve at REMOVE-THIS-cybersource.com.au
Sun Aug 30 12:44:48 CEST 2009
On Sun, 30 Aug 2009 01:01:37 -0700, Mark Dickinson wrote:
> On Aug 29, 8:03 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote:
>> > I thought that int as object will stay the same object after += but
>> > with another integer value. My intuition said me that int object
>> > which represent integer value should behave this way.
>> If it did, then you would have this behaviour:
>> >>> n = 3 # bind the name n to the object 3
>> >>> saved_id = id(n) # get the id of the object n += 1
>> >>> # add one to the object 3 assert n == 4 #
>> >>> confirm that it has value four assert id(n) == saved_id # confirm
>> >>> that it is the same object m = 3 # bind the
>> >>> name m to the object 3 print m + 1 # but object 3 has
>> >>> been modified
> I don't see how that follows.
Okay, it follows given Python's caching of small integer objects.
It also follows from the idea that there is one abstract entity which
English speakers call "three" and write as 3. There's not two identical
entities with value 3, or four, or a million of them, only one.
But of course your alternative implementation (where every time the
Python VM sees the literal 3 it creates a new integer object with that
value) would also be a valid, albeit inefficient, implementation. To be
honest, I didn't even think of that.
More information about the Python-list