copy on write
John O'Hagan
research at johnohagan.com
Wed Feb 1 22:18:12 EST 2012
On Fri, 13 Jan 2012 10:40:47 -0800
Ethan Furman <ethan at stoneleaf.us> wrote:
> Steven D'Aprano wrote:
> > Normally this is harmless, but there is one interesting little
> > glitch you can get:
> >
> >>>> t = ('a', [23])
> >>>> t[1] += [42]
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in <module>
> > TypeError: 'tuple' object does not support item assignment
> >>>> t
> > ('a', [23, 42])
IMHO, this is worthy of bug-hood: shouldn't we be able to conclude from the TypeError that the assignment failed?
> There is one other glitch, and possibly my only complaint:
>
> --> a = [1, 2, 3]
> --> b = 'hello, world'
> --> a = a + b
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: can only concatenate list (not "str") to list
> --> a += b
> --> a
> [1, 2, 3, 'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>
> IMO, either both + and += should succeed, or both should fail.
>
> ~Ethan~
This also happens for tuples, sets, generators and range objects (probably any iterable), AFAIK only when the left operand is a list. Do lists get special treatment in terms of implicitly converting the right-hand operand?
The behaviour of the "in-place" operator could be more consistent across types:
>>> a=[1,2]
>>> a+=(3,4)
>>> a
[1, 2, 3, 4]
>>> a=(1,2)
>>> a+=(3,4)
>>> a
(1, 2, 3, 4)
>>> a=(1,2)
>>> a+=[3,4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
John
More information about the Python-list
mailing list