4. Simultaneous state updates

This pattern makes code more concise and avoids nuisance variables. In the first approach, temporary variables are used to stage updates. In the second, the related updates happen together in one assignment.

Bundling related assignments can also avoid transient intermediate states that do not really exist in the intended logic. It is a good fit when several names are being updated as one conceptual step.

4.1. Don’t do this

1x, y = 1, 2
2temp = x
3x = y
4y = temp
 1def update_x(x):
 2    return x + 1
 3
 4def update_y(y):
 5    return y + 1
 6
 7x = 3
 8y = 4
 9dx = 4
10dy = 5
11
12tmp_x = x + dx
13tmp_y = y + dy
14tmp_dx = update_x(x)
15tmp_dy = update_y(y)
16
17x = tmp_x
18y = tmp_y
19dx = tmp_dx
20dy = tmp_dy
21
22print(x, y, dx, dy)

4.2. Do this

1x, y = 1, 2
2x, y = y, x
 1def update_x(x):
 2    return x + 1
 3
 4def update_y(y):
 5    return y + 1
 6
 7x = 3
 8y = 4
 9dx = 4
10dy = 5
11
12x, y, dx, dy = (x + dx, y + dy, update_x(x), update_y(y))
13
14print(x, y, dx, dy)