Why I need to declare import as global in function

Fredrik Lundh fredrik at pythonware.com
Wed Nov 30 13:36:15 EST 2005


Dennis Lee Bieber wrote:

> > But the solutions already proposed seems to work file for my sample
> > program. I will try on my project soon :)
>
> Looking at the documentation for "execfile", I can see /how/ the
> problem occurs -- but can't determine if this can be considered
> "expected".
>
> -=-=-=-=-=-=-
> execfile( filename[, globals[, locals]])
>
> This function is similar to the exec statement, but parses a file
> instead of a string. It is different from the import statement in that
> it does not use the module administration -- it reads the file
> unconditionally and does not create a new module.2.2
> -=-=-=-=-=-=-
>
> I'm guessing that the intent was only that "file 1" not become an
> entry on the module list, but it seems to be applying "...not create a
> new module" recursively to the imported "math"... Maybe an expert with
> the Python byte-code can verify. My hypothesis is something on the order
> of:
> Outer (file level) references to math (math.pi) are being handled
> during the byte-code compilation phase of execfile, so even if "math"
> isn't in the module list, it is still in local scope for the outer
> math.pi...

the byte code is identical for both cases; the only difference I can see is
that when when you compile a function that contains a global statement,
the corresponding name is added to the globals for the function that does
the compilation (run_ut in this case).

if you don't use globals, or if the "global" name doesn't exist in the module
namespace, this doesn't happen.

hmm.   puzzling.

</F>






More information about the Python-list mailing list