newbie looking for help, int reference question

Jp Calderone exarkun at intarweb.us
Wed Jan 15 00:42:23 EST 2003


On Wed, Jan 15, 2003 at 07:15:15AM +1300, Andrew McGregor wrote:
> 
> [snip]
> 
> Assignment is a statement (not an expression) which binds the name(s) on 
> the LHS to the value(s) on the RHS.  The += forms mean the same as their 
> expansion, so
> 
> i += 10
> 
> really is the same as
> 
> i = (i + 10)
> 
> and means 'rebind the name i to the object returned by the expression i + 
> 10'
> 

   Ahhh, no.  += is only sometimes semantically equal to the ... = ... + ...
expansion.  This is the source of much confusion, and a good reason to avoid
+= altogether.  Here are a few examples to demonstrate...

def foo(x, y):
    x += y
    return x

foo(10, 20)
x = foo([], range(3))
print x
print foo(x, x)
print x

  And, of course, my personal favorite:

x = ([],)
x[0] += [None]
print x

  This doesn't have much to do with the original question, but if the use of
+= is avoided, the behavior exhibited should become quite clear.

  Jp

-- 
Lowery's Law:
        If it jams -- force it.  If it breaks, it needed replacing anyway.
--
 12:00am up 30 days, 9:47, 3 users, load average: 0.39, 0.25, 0.25
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030115/ac38949f/attachment.sig>


More information about the Python-list mailing list