Is behavior of += intentional for int?

Tim Roberts timr at probo.com
Wed Sep 2 03:07:27 EDT 2009


Steven D'Aprano <steve 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
>5
>
>This would be pretty disturbing behaviour, and anything but intuitive.

Yes, indeed, and it's quite possible to write code like this in Fortran
that produces exactly this result -- an integer constant gets modified.

This used to get big yucks when we gathered around the keypunch, before we
had the Obfuscated C Contest to amuse us.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list