There are many opportunities for the walrus operator to simplify code, but my go-to party trick is below.
Example
# Bad
with open('file.txt', 'r') as fd:
chunk = fd.read(1024)
while chunk:
do_stuff(chunk)
chunk = fd.read(1024)
# Good
with open('file.txt', 'r') as fd:
while (chunk := fd.read(1024)):
do_stuff(chunk)
In general:
# Bad
x = ...
# no other use of x
if x: # or while, if it assigns x in a similar way
# do stuff with x
# no further use of x
# Good
if (x := ...): # or while, if it assigns x in a similar way
# do stuff with x
# no further use of x
Explanation
There are many opportunities for the walrus operator to simplify code, but my go-to party trick is below.
Example
In general: