Is behavior of += intentional for int?

Mark Dickinson dickinsm at gmail.com
Sun Aug 30 04:01:37 EDT 2009


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
>
> 5

I don't see how that follows.  In an alternative interpretation, the
int literals would all be thought of as distinct objects:  that is,
the line 'n = 3' creates an integer object with value 3 and binds the
name n to it;  the later line 'm = 3' then creates another *new*
integer object with value 3 and binds the name m to it.  In other
words, it could work in exactly the same way as the following works in
Python:

>>> n = {}
>>> n[1729] = 10585
>>> m = {}
>>> m
{}

The modification to n doesn't affect m, since the two occurrences of
{} give distinct dictionary objects.

--
Mark



More information about the Python-list mailing list