A += B Assignment Riddle in Python

PythonServer Side ProgrammingProgramming

In this chapter we see what happens when we update the values in a tuple, which is actually immutable. We will be able to merge new values with old values but that throws an error. We can study the bytecode of the error and understand better how the rules for tuple work.

First we define a tuple and then issue a command to update its last element as shown below.

Example

>>> tupl = (5,7,9,[1,4])
>>> tupl[3] += [6,8]

Output

Running the above code gives us the following result −

Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> tupl
(5, 7, 9, [1, 4, 6, 8])

Now we to study the byte code of above approach we put the code into a function and apply the dis method to display the byte code. We get the same error but with more details.

Example

def immut_function():
   tupl = (5,7,9,[1,4])
   tupl[3] += [6,8]
immut_function()

Output

Running the above code gives us the following result −

TypeError Traceback (most recent call last)
in ()
      2 tupl = (5,7,9,[1,4])
      3 tupl[3] += [6,8]
----> 4 immut_function()
in immut_function()
      1 def immut_function():
      2 tupl = (5,7,9,[1,4])
----> 3 tupl[3] += [6,8]
4 immut_function()
TypeError: 'tuple' object does not support item assignment

Next we display the bytecode of the above function to see the details of the tuple assignment and errors.

Example

import dis
dis.dis(immut_function)

Output

Running the above code gives us the following result −

2   0 LOAD_CONST      1 (5)
    3 LOAD_CONST      2 (7)
    6 LOAD_CONST      3 (9)
    9 LOAD_CONST      4 (1)
   12 LOAD_CONST      5 (4)
   15 BUILD_LIST      2
   18 BUILD_TUPLE     4
   21 STORE_FAST   0 (tupl)
    3 24 LOAD_FAST   0 (tupl)
   27 LOAD_CONST 6 (3)
   30 DUP_TOPX 2
   33 BINARY_SUBSCR
   34 LOAD_CONST 7 (6)
   37 LOAD_CONST 8 (8)
   40 BUILD_LIST 2
   43 INPLACE_ADD
   44 ROT_THREE
   45 STORE_SUBSCR
   46 LOAD_CONST 0 (None)
   49 RETURN_VALUE

The conclusion is not to put mutable elements into a tuple. Though assignment is possible, it throws an exception. As shown in the step with value 46, the assignment fails as tuple is a immutable object.

raja
Published on 07-Aug-2019 10:46:46
Advertisements