function object.func_default off the console

Peter Otten __peter__ at web.de
Thu Apr 26 12:08:21 EDT 2007


castironpi at gmail.com wrote:

> On Apr 25, 1:56 am, Peter Otten <__pete... at web.de> wrote:
>> Aaron Brady wrote:
>> >>>> f.func_defaults[0]
>> > [2, 3]
>> >>>> f.func_defaults[0]+=[4]
>> > Traceback (most recent call last):
>> >    File "<stdin>", line 1, in <module>
>> > TypeError: 'tuple' object does not support item assignment
>> >>>> f.func_defaults[0]
>> > [2, 3, 4]
>>
>> > V. interesting.  Operation succeeds but with a throw.  Er, raise.
>>
>> This is not specific to func_defaults:
>>
>> >>> t = ([1],)
>> >>> t[0] += [2]
>>
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: 'tuple' object does not support item assignment>>> t
>>
>> ([1, 2],)
>>
>> t[0] += [2]
>>
>> is resolved to
>>
>> t.__setitem__(t[0].__iadd__([2]))
>>
>> where list.__iadd__() succeeds but __setitem__() fails (because tuples
>> don't have that method).
>>
>> Peter
> 
> Curious why t.__setitem__ is called.  Wouldn't it still refer to the
> same list?

How is Python to know? Consider

>>> items = [[], 0]
>>> items[0] += [42] # could do without __setitem__()
>>> items[1] += 42   # __setitem__() required
>>> items
[[42], 42]

When the item is immutable the += operation can only work by replacing it
with another value. 

Peter




More information about the Python-list mailing list