Python Gotcha's?

John O'Hagan research at johnohagan.com
Thu Apr 5 23:44:33 EDT 2012


On Thu, 05 Apr 2012 10:15:03 -0400
John Posner <jjposner at optimum.net> wrote:

> On 4/4/2012 7:32 PM, Chris Angelico wrote:
> > Don't know if it's what's meant on that page by the += operator,
> 
> Yes, it is.
> 
> >> a=([1],)
> >> a[0].append(2) # This is fine
> 
> [In the following, I use the term "name" rather loosely.]
> 
> The append() method attempts to modify the object whose name is "a[0]".
> That object is a LIST, so the attempt succeeds.
> 
> >> a[0]+=[3] # This is not.
> 
> The assignment attempts to modify the object whose name is "a". That
> object is a TUPLE, so the attempt fails. This might be a surprise, but
> I'm not sure it deserves to be called a wart.

There was a thread called "copy on write" several weeks ago which veered into a
discussion of this:

http://mail.python.org/pipermail/python-list/2012-January/1286466.html

While I follow the reason for the exception noted above, to me this is a gotcha,
and has at least two wart-like features:

1) The mutation clearly intended by a[0] += [3] succeeds, even though an
exception is raised. What fails is the subsequent assignment, which makes no
difference in this case. I wouldn't blame anyone for being surprised to find
that a[0] is now [1, 2, 3] despite the exception.

2) Whether the operation succeeds depends on what name we use to refer to the
object:

>>> a = ([],)
>>> b = a[0]
>>> b is a[0]
True
>>> b += [1]
>>> a
([1],)
>>> a[0] += [2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
([1, 2],)
>>> b is a[0]
True

Very surprising to me, despite knowing why it happens. I used to believe that
how an object is referred to had no effect on its behaviour as an operand.

In the abovementioned thread, Hrvoje Niksic posted an implementation approach
which avoided all this by "simply not perform[ing] the final assignment if the
in-place method is available on the contained object":

http://mail.python.org/pipermail/python-list/2012-February/1287400.html

However, I get the impression this issue is generally regarded as "least worst,
won't fix".

Regards,

John 



More information about the Python-list mailing list