imported module no longer available

Fredrik Lundh fredrik at pythonware.com
Mon Jul 21 10:19:23 EDT 2008


Jeff Dyke wrote:

> I've come across an error that i'm not yet able to create a test case
> for but wanted to get see if someone could shed light on this.
> 
> I have imported a module at the top of my file with
> import mymodulename
> 
> this module is used many times in the current file successfully, but
> then I attempt to use it one more time and get: UnboundLocalError:
> local variable 'mymodulename' referenced before assignment

Let me guess: you've done

     def myfunc():
         print mymodulename
         import mymodulename

or something similar?  Getting an exception in this case is the excepted 
behaviour; the reason being that a variable in a block only belongs to a 
single scope. for the entire block.  For details, see:

     http://docs.python.org/ref/naming.html

Especially this section:

"If a name binding operation occurs anywhere within a code block, all 
uses of the name within the block are treated as references to the 
current block. This can lead to errors when a name is used within a 
block before it is bound. This rule is subtle. Python lacks declarations 
and allows name binding operations to occur anywhere within a code 
block. The local variables of a code block can be determined by scanning 
the entire text of the block for name binding operations."

To fix this, mark the name as global:

     def myfunc():
         global mymodulename # I mean the global name!
         print mymodulename
         import mymodulename

</F>




More information about the Python-list mailing list