Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is an unbound variable error warning by IDE in this simple python function

Very simple question, but I can't find the answer to it. My IDE vs code (pylance) give me the warning/hint for a being possibly unbound. Why is this? How do I fix it?

def f():
    for i in range(4):
        a = 1
        print(a)

    return a
like image 799
Gang Avatar asked Aug 13 '20 04:08

Gang


Video Answer


1 Answers

Because range(4) might be something empty (if you overwrite the built-in range), in which case the loop body will never run and a will not get assigned. Which is a problem when it's supposed to get returned.

Maybe you can tell your IDE to ignore this and not show the warning. Or assign some meaningful default to a before the loop.

like image 152
superb rain Avatar answered Oct 25 '22 01:10

superb rain