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

1

13

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
Cyanohydrin answered 13/8, 2020 at 4:56 Comment(4)
Your code is invalid, enumerate takes iterable as input you can't pass int may be you need a range.Diphthongize
enumerate(4)? That's not going to work. The warning means that you should take into account that a for loop can run 0 times and a would be undefined.Mccully
@Sushanth, @Klaus I have changed it to rangeCyanohydrin
You can add a=None before the for loopSucceed
C
26

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.

Carlyn answered 13/8, 2020 at 5:20 Comment(1)
If you assign e.g. None before the loop, you can assert is not None afterwards to get the inferred type from int | None back to int and still catch errors early where the loop indeed didn't execute (instead of returning the None default value).Shore

© 2022 - 2024 — McMap. All rights reserved.