Is behavior of += intentional for int?
pavlovevidence at gmail.com
Wed Sep 2 14:40:51 CEST 2009
On Sep 2, 12:07 am, Tim Roberts <t... at probo.com> wrote:
> 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
> >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.
Many Fortran compilers these days pass scalars by value by default.
Recently I had to compile a cicra-1972 Fortran program where I had to
disable a lot of recent Fortran innovations (like from 1977) to get it
to build properly. It turned out that it did try to modify a constant
somewhere, but then it segfaulted because the compiler put that
constant in read-only memory.
(Whoever wrote the program originally was a smart cookie, BTW, it was
super versatile for its time.)
More information about the Python-list