pyflakes icon indicating copy to clipboard operation
pyflakes copied to clipboard

False positive for `F841 Unused variable` when using assignment expressions

Open jcarlosroldan opened this issue 8 months ago • 2 comments

This example from the PEP 572 incorrectly reports the total variable as unused:

def cumulative_sum(values):
    total = 0
    return [total := total + v for v in values]

jcarlosroldan avatar Jun 11 '25 08:06 jcarlosroldan

The actual example is

# Compute partial sums in a list comprehension
total = 0
partial_sums = [total := total + v for v in values]
print("Total:", total)

In this case you're not using total after words which is why I believe we're flagging this.

That said, I think this is technically valid, if not horrible to read and comprehend

sigmavirus24 avatar Jun 11 '25 10:06 sigmavirus24

@sigmavirus24 it is valid indeed. I also wrapped it into a function so that total is not a global variable that won't raise an F841 either.

jcarlosroldan avatar Jun 11 '25 11:06 jcarlosroldan