__iadd__ and fellows missing (Python 2.2)

Philip Swartzleonard starx at pacbell.net
Sat Apr 13 07:09:47 EDT 2002


Ralf Juengling || Sat 13 Apr 2002 03:27:20a:

> Michael Hudson <mwh at python.net> writes:
> 
>> Ralf Juengling <juenglin at informatik.uni-freiburg.de> writes:
>> 
>> > Shouldn't I find the special methods '__iadd__' et al, when
>> > asking for the attributes of 'int'?
>> 
>> ints are immutable, so they don't implement __iadd__.  lists do:
>> 
> 
> Hm. But then an expression 'i+=1' should cause an error if 'i'
> is an int...
> 
>>>> i = 1
>>>> type(i) 
> <type 'int'>
>>>> id(i)
> 134526912
>>>> i+=1
>>>> id(i)
> 134526852
>>>> 
> 
> I understand now, that 'i+=1' is no real in-place operation but
> just a shortcut for 'i=i+1' since int is immutable. The language
> reference states that this is okay, anyhow, I find it confusing.
> 
> For the sake of clarity, an 'in-place' operation should really 
> work in-place, don't you think?

Even though it can't? I'm guessing that you mean that id(i) should be 
the same before and after i+=1? My first reaction would be that you'd 
need to create another variable anyway, before doing the add, and moving 
it back to where the original was would be too expensive for such a 
simple operaiton.

However it appears the real reason is far wierder; observe:

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> a = 1
>>> b = 2
>>> c = 2
>>> id(a)
7692256
>>> id(b)
7692232
>>> id(c)
7692232
>>> b is c
1
>>> a += 1
>>> id(a)
7692232
>>> a is b
1

It appears that python only kees one copy of any given int around, and 
any name that happens to gain the status of being that integer really 
just gets another copy of it's pointer. It seems like it'd be less 
effort, but...

-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list