python assignment

dan danbmil99 at yahoo.com
Wed Jul 23 03:44:33 EDT 2003


Ok, thanks for the responses.  I think I 'get' it now.  However I do
think it would be an excellent idea to have a bit of exposition on
this subject in the Python tutorial, or perhaps in a separate section.
 It's not really hard to understand once you realize what's going on,
but I suspect it causes no end of confusion for both new programmers
and old (those used to langs such as C++).

Here's a better example of how a newbie can get confused:

>>> a = (1,2)      #a is a tuple
>>> b = a          #b & a now point to same object on heap
>>> a += (3,)      #tuples are immutable so += returns a new one
>>> b == a         #b points to old, a points to new
False
>>> a = [1,2]      #a is a list
>>> b = a          #a & b point to same object again
>>> a += [3]       #a is mutable, so += mutates it
>>> b == a         #of course
True
>>> a = a + [4]    #hmm... one *might* think this is eqiv. to a += [4]
>>> a == b
False              #but NOOO!!
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3]

Now that I understand what's happening, it makes sense, but initially
this sort of behavior was quite mysterious.

-dbm

danbmil99 at yahoo.com (dan) wrote in message news:<fbf8d8f2.0307221659.1dd1ac77 at posting.google.com>...
> without stirring the pot too much --
> 
> could someone please point me to whatever documentation exists on the
> philosophy, semantics, and practical implications of how Python
> implements the assignment operator?  So far I can't find much useful
> in the regular documentation.  I understand the basic concept that
> names are bound to objects which exist on the heap, but that still
> doesn't explain why a = b doesn't _always_ cause a to point to the
> same object as b.  What determines when the object in question is
> copied?  What determines when a future maniplulation of the variable
> will cause it to point to an object that is already referenced by
> another variable? (see code below for an example).
> 
> What I need is an exact and unambiguous algorithm for determining when
> an assignment will change the id of the variable (or should I say,
> when the evaluation of an expression will cause a new object to be
> created).  Some of the issues involved can be discerned from the
> following session:
> 
> >>> a = 1
> >>> b = a
> >>> a is b
>  True
> >>> a += 1
> >>> a -= 1
> >>> a is b
>  True
> >>> a = 1.0
> >>> b = a
> >>> a is b
>  True
> >>> a += 1
> >>> a -= 1
> >>> a is b
>  False
> >>> a == b
> True




More information about the Python-list mailing list