A good application of an assignment expression is the reuse of a value that may be expensive to calculate, for example in a list comprehension:
filtered_values = [f(x) for x in values if f(x) >= 0]
Here, the :=
operator can be used to assign the returned value of f(x)
at the same time as checking if it is positive:
filtered_values = [val for x in values if (val := f(x)) >= 0]
As a further example, consider the following block of code, which reads in and processes a large file in chunks of 4 kB at a time:
CHUNK_SIZE = 4096
chunk = fi.read(CHUNK_SIZE)
while chunk:
process_chunk(chunk)
chunk = fi.read(CHUNK_SIZE)
This can be written more clearly as
while chunk := fi.read(CHUNK_SIZE):
process_chunk(chunk)
(Note that in this case it is not necessary to enclose the assignment expression in parentheses).