44. Simultaneous state updates
The key here is to make your code more concise and avoid nuisance variables. In the discouraged approach, you create temporary variables to avoid mutating x and y. In the encouraged approach, all mutations occur in one coherent line.
44.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)
44.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)