Unbound local variable warning when it should not happen

Answered

Consider the following snippet:

def f():
check = True
if check:
var_bound_to_check = 100

for i in range(10):
if not check:
print i, "not check"
else:
print i, var_bound_to_check

In the last line, `var_bound_to_check` has a "Local variable `var_bound_to_check` might be referenced before assignment" warning. This is kind of annoying because it is not true. The only way to solve it is to declare `var_bound_to_check` with a dummy value before the `if check` outside of the loop, but this totally break the perks of scopes in Python.

Is there any way to solve it?

0
2 comments

Please, file an issue about it to PyCharm bug-tracker: https://youtrack.jetbrains.com/issues/PY, thank you.

0

Perhaps I'm mistaken, but isn't this done on purpose?

Since you're declaring ``var_bound_to_check`` within an ``if`` statement, it suggests there is a possibility that the variable could not be bound. Yes, I understand that the line above it clearly shows the check is true, but consider this code:

check = True if somecondition else False
if check:
var_bound_to_check = 100

At that point, It would be perfectly reasonable for the editor to point out "Local variable might be referenced before assignment."

Perhaps it's nitpicky on my part, but interpreted the statement as being true because of the word 'might' rather than 'is'. I figured this as being a part of inspection logic that was 'better safe than sorry' and avoided ambiguity.

0

Please sign in to leave a comment.