Re: imported module no longer available

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fredrik Lundh

    Re: imported module no longer available

    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: UnboundLocalErr or:
    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:



    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>

Working...