imported module no longer available

Mark Tolonen M8R-yfto6h at
Mon Jul 21 16:09:13 CEST 2008

"Jeff Dyke" <jeff.dyke at> wrote in message 
news:mailman.406.1216648575.922.python-list at
> 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
> if i add `print globals().keys()` right before the line where the
> error occurs l see the module in the list (actual output, names
> changed to protect the innocent)
> ['HPADao', 'RDao', 'DriverBase', 'FKSUtility', 'PMDao',
> 'mymodulename', 'IDriver', 'DriverTrack', 'HPPDao', 'setLogName',
> 'HPDao', 'iparser', '__builtins__', '__file__', 'driver', '_LOGNAME',
> 'sys', 'IClient', '__name__', 'copy', 'types', 'logging', 'iloader',
> 'HPADao', '__doc__', 'PMDao', 'time', 'FormatLoad']
> Traceback (most recent call last):
>  File "", line 475, in <module>
>    driver.getRData('0605', 22528)
>  File "", line 256, in getRData
>    print mymodulename
> the code that generates these two lines is:
> print globals().keys()
> print mymodulename
> I can solve this by placing
> import mymodulename again in this method, but can't have that everywhere.
> I will try to come up with a generic reproduction of this issue, but
> that might take some time.  I've also seen this in the past with the
> python builtin 'sys'
> I did see a bug, which has very
> similar behaviour, but is different.
> Python 2.5, ubuntu hardy
> Thanks for any insight,
> Jeff

That error will occur if somewhere in a function or method you accidently 
assign another value to a global variable, without declaring it with the 
global keyword first, even if it occurs later in the function.  Example:

    import os
    print os.getcwd()
    def func():
        print globals().keys()
        print os


    ['__builtins__', '__file__', 'func', '__name__', 'os', '__doc__']
    Traceback (most recent call last):
line 414, in ImportFile
        exec codeObj in __main__.__dict__
      File "<auto import>", line 1, in <module>
      File "", line 10, in <module>
      File "", line 7, in func
        print os
    UnboundLocalError: local variable 'os' referenced before assignment

Check in the function that caused the error to see if later in the code the 
module name is being used as a local variable.


More information about the Python-list mailing list