Connecting Tech Pros Worldwide Forums | Help | Site Map

Re: imported module no longer available

Fredrik Lundh
Guest
 
Posts: n/a
#1: Jul 21 '08
Jeff Dyke wrote:
Quote:
Quote:
>actually no, the only things in that fucntion were.
> print globals().keys() - i see it here
> print mymodulename - it fails here.
>>
>the `import mymodulename` statement is at the very top of the file.
>>
>plus the processing that was attempted after.
so how did that processing use the "mymodulename" name?
Quote:
Quote:
>in fact in the calling
>method i was able to execute print mymodulename and it printed the
>expected python output.
the calling method has nothing to do with what's considered to be a
local variable in the method being called, so that only means that the
name is indeed available in the global scope.
Quote:
Quote:
>So i went back to check that the name 'mymodulename' was not getting
>overwritten by something else and the error went away. I've been
>working on something else entirely for the past few hours and have
>changed none of the code...and now it works. which is even more
>troublesome then the error itself.
more likely, it indicates that you removed the line that caused Python
to treat that name as a local variable.
Quote:
Quote:
>Follow on question. If this name, mymodulename, was imported in some
>other module.fucntion local to a function like
>def anotherfunc():
> import mymodulename
>>
>would that remove it from the globals() and save it to a locals() ? I
>would assume the answer to be no.
even after reading the page I pointed you to?

import binds a name, so an import statement inside a function will cause
Python to treat that name as a local variable (unless you add a global
declaration to that function).

maybe a few examples will make this clearer; the following snippets are
complete programs:

snippet 1:

import module # adds module to the global namespace

def func():
module.func() # uses module from the global namespace

func() # no error here

snippet 2:

def func():
import module # adds module to the *local* namespace
module.func()

func() # no error here
module.func() # doesn't work; no module in global namespace

snippet 3:

def func():
global module # marks module as a global name
import module # adds module to the *global* namespace
module.func()

func() # no error here
module.func() # no error here; global module set by function

snippet 4:

import module # adds module to global namespace

def func():
import module # adds module to local namespace too
print module # prints local variable
module = None # sets local variable to None

func() # no error here
module.func() # no error here either; uses global namespace

snippet 5:

import module

def func():
print module # fails with an UnboundLocalError.
# lots of lines
import module # adds to local namespace; marks name as local
# some more code

func() # will fail at print statement

my guess is that the last snippet corresponds to your case.

</F>


Closed Thread