7. Use the walrus operator to avoid repeated work in conditions

When a condition also needs the computed value, := can be clearer than computing the same result twice.

The walrus operator is most helpful when a condition naturally produces a value you need immediately afterward. Used this way, it removes duplicated calls and keeps the read-test-use flow together, but it should stay local and simple rather than turning a condition into a dense expression.

Note

Python 3.8+

7.1. Don’t do this

1line = input_stream.readline()
2while line != '':
3    print(line.strip())
4    line = input_stream.readline()

7.2. Do this

1while (line := input_stream.readline()) != '':
2    print(line.strip())