MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
185 stars 19 forks source link

[New Rule] Promote the walrus operator on >3.8 #68

Open ROpdebee opened 3 years ago

ROpdebee commented 3 years ago

Explanation

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