Reputation: 323
I have a question regarding the error local variable ... referenced before assignment in Python3. Several cases of this error have been discussed in this forum (look at here); however they don't address my question. My problem at the moment is not how to resolve this issue, but to understand why there is such an issue.
Here is my code:
class Test:
def __init__(self,n):
if n > 0:
self.index = n
self.check = v[0]
else:
self.index = n+5
self.check = v[1]
v = [18,12]
v = [90,43]
g = Test(18)
The problem arises only because of that v=[18,12]
assignment. If it is erased, there won't be any error. However, my issue is that 18 > 0, and as a result, the part of the code that comes after the else
must be ignored. Thus, why is there such an error?
Upvotes: 0
Views: 1487
Reputation: 230561
want to know why there is an error at all
The problem is that your assignment creates a local variable v
, that shadows your global variable v
. This happens at parse/load time. That's why python knows that you tried to use the local variable before giving it any value.
Upvotes: 2