1

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
ensnare
  • 40,069
  • 64
  • 158
  • 224

1 Answers1

6

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:

import user

class Thing(object):

    def doSomething(self):
        u = user.User(1)
        print u.name
        # ...
        user = something

The problem is that by assigning to the local name user you've said that user is a local variable for the entire body of that function -- even the code before the assignment. This means that the name user does 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 user ensures that the "user" module has been imported, and assigns that module object to the name user.

The simple fix is to change the name of your local variable to something that doesn't shadow your import.

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • Eesh ok, I'm trying to figure out the relevant parts to post without posting a million classes / lines. – ensnare Dec 10 '10 at 00:43
  • I was trying to figure out how that specific exception could be thrown instead of a `NameError`. Try `import user as USER` and change all of the references in the source that is failing. It might be easiest to triage that way. – D.Shawley Dec 10 '10 at 00:48
  • You read my code without me having to paste it all -- thanks so much. Really appreciate it. This worked! – ensnare Dec 10 '10 at 00:48