import namespace issues

Alex Martelli aleaxit at
Tue Jul 10 11:33:21 CEST 2001

"Harald Kirsch" <kirschh at> wrote in message
news:yv2lmlxgnji.fsf at
> I have to separate a module's function into two .py-files. Now I would
> like to import both in a way that they behave like they are one file.

This is likely to lead to maintenance problem -- what is the
advantage of splitting things in two if you then go out of
your way to couple the two as strongly as possible?  And mutual,
aka cyclic, dependencies, too -- the worst kind...

> Suppose the files are called and I put a
>   from import *

No .py here -- just "from second import *".

> into This does not work as necessary since functions in
> don't find functions defined in Same story when

Perhaps you can synchronize the two dictionaries at this point
by segue-ing with
    import second
but this will NOT ensure that any LATER changes to the __dict__
of either module are somehow "magically synchronized".

> using __import__().
> What I gathered from experiments is that even with `from ... import'
> as well as when using __import__('second', my_globals, my_locals)
> there will *always* be a *new* dictionary used for the globals() of
> the imported functions. Example:

To be precise: every module object has a __dict__ attribute that
is NOT rebindable.  globals() just returns the __dict__ of the
module object from which globals() is being called.  __import__
uses its dictionary arguments in different ways than you seem to
believe it's using them.

> How can I achieve to merge two .py into one globals() as if the were
> in one imported file while maintaining the file-search semantics of
> `import'?

I don't think you can ever possibly make any module object
use a different dictionary than the one it was born with.  You
can try to fake it in several ways (e.g., an *instance* object
does have a re-bindable __dict__ attribute), but I think there
will be correct programs that behave otherwise under the fake-it
scenarion than they would if the two modules were indeed one.

> Is there a detailed description somewhere in the docs about the
> namespaces (or dictionaries) used/created/shuffled during an import?

I think the documentation for __import__ is pretty clear about
it, "the standard implementation does not use its locals argument
at all, and uses its globals only to determine the package context
of the import statement".


More information about the Python-list mailing list