Could you explain this rebinding (or some other action) on "nums = nums"?

Denis McMahon denismfmcmahon at gmail.com
Tue Dec 1 16:37:56 EST 2015


On Tue, 01 Dec 2015 14:44:38 -0600, Ian Kelly wrote:

> On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon <denismfmcmahon at gmail.com>
> wrote:
>> On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote:
>>
>>> In the case of:
>>>
>>>      tup[1] += [6, 7]
>>>
>>> what it's trying to do is:
>>>
>>>      tup[1] = tup[1].__iadd__([6, 7])
>>>
>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>>> then Python tries to put the result that the method returns into
>>> tup[1].
>>> That fails because tup itself is a tuple, which is immutable.
>>
>> I think I might have found a bug:
>>
>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
>> for more information.
>>>>> tup = [1,2,3],[4,5,6]
>>>>> tup
>> ([1, 2, 3], [4, 5, 6])
>>>>> tup[1]
>> [4, 5, 6]
>>>>> tup[1] += [7,8,9]
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: 'tuple' object does not support item assignment
>>>>> tup[1]
>> [4, 5, 6, 7, 8, 9]
>>>>> tup
>> ([1, 2, 3], [4, 5, 6, 7, 8, 9])
>>>>> quit()
> 
> No, that's the expected result. As MRAB wrote, the list *is* mutated
> when its __iadd__ method is called. The TypeError happens afterward when
> the assignment is attempted.

The assignment succeeds. That's imo a bug. If it's a TypeError to try and 
assign a value to tup[1], then tup[1] should not allow the mutated list 
to be assigned.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list