Undefined variable defined later in a loop

Bug #1686327 reported by asmeurer
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Pyflakes
Won't Fix
Undecided
Unassigned

Bug Description

For the following code

def test():
    a = False
    for i in range(10):
        if a:
            print(b)
        else:
            a = True
            b = 1

pyflakes gives the following errors

test.py:5: undefined name 'b'
test.py:8: local variable 'b' is assigned to but never used

But test() runs just fine without any errors.

Revision history for this message
Phil Frost (bitglue) wrote :

Here we know a is False because it was assigned with a literal. But what if it's the result of a function call, or even a more complex expression?

Have you encountered this in the wild?

Revision history for this message
asmeurer (asmeurer) wrote :

I hit it in my own code. But, honestly, it's a very unstable coding pattern. I ended up adding a minor thing to it which required defining the variable before the loop. So if fixing this is too hard or adds too many false negatives I wouldn't be too worried about it.

Revision history for this message
Phil Frost (bitglue) wrote :

Yeah, I think it would be pretty tricky. Right now pyflakes skips over conditional branches as if they aren't even there, so all it sees is:

    a = False
    print(b)
    a = True
    b = 1

Technically it could be fixed when `a` is assigned a literal, but between the effort required to implement the fix and the added complexity to the code I don't think it's worthwhile.

Changed in pyflakes:
status: New → Won't Fix
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.