Example:
import user
class Thing(object):
def doSomething(self):
u = user.User(1)
print u.name
>> UnboundLocalError: local variable 'user' referenced before assignment
But this works:
class Thing(object):
def doSomething(self):
import user
u = user.User(1)
print u.name
Thanks for your help!
Edit:
But this works:
import user as anothername
class Thing(object):
def doSomething(self):
u = anothername.User(1)
print u.name
The code you’ve posted is missing something, because it works fine as shown.
I’m guessing that your real code looks more like this:
The problem is that by assigning to the local name
useryou’ve said thatuseris a local variable for the entire body of that function — even the code before the assignment. This means that the nameuserdoes not refer to your module in that function, it refers to a local variable. Trying to reference a local variable before it’s been assigned a value results in the error you’re seeing.Using a local import works because part of what import does is assignment. ie:
import userensures that the “user” module has been imported, and assigns that module object to the nameuser.The simple fix is to change the name of your local variable to something that doesn’t shadow your import.