Module import information

Eric White eswhite at
Tue Mar 21 18:04:41 CET 2006


Thanks for the reply.  Consider the following situation:

A set of variable names is defined along with a list of possible values for
each.   A second set of variable names is defined along with an expression
for generating a value for each.  For each possible permutation of variables
from the first set, a python script is created that contains commands that
initialize the variable set with the permuted values.  A second python
script is created that contains commands for connecting to a database and
storing the values of the second set of variables after running the
associated expression for each.

We would like to be able to use the scripts above to drive a python script
containing a system of equations specified at run time and to store the
results.  This "master" script contains the following calls:

import somemodule

# do stuff ...

# initialize permuted variables

# do more stuff ...

# store results

# do more stuff ... Etc.

We would like for the call to init to initialize variables in the context of
the "master" script.  To do this inside somemodule we use the
sys.modulesdictionary to find a reference to the master module by name
and initialize
variables at this reference.

What I would like to know if it is arbitrarily possible to "walk" the import
hierarchy from any point.  It is not apparent that python's optimization of
subsequent imports of the same module is relavent.

On 3/21/06, Peter Hansen <peter at> wrote:
> Eric White wrote:
> > Is it possible to determine the name of the module that invoked import
> > from within the imported module?
> Almost anything is possible in Python.  On the other hand, some things
> are probably impractical, and others ill-advised.  Perhaps you can
> describe your requirements, *why* you want to do this, to provide some
> context for the answers.
> Also, consider that the effect of the import statement is different
> after the first import.  When an already-imported module is imported by
> another module (i.e. the second time "import xxx" is executed for your
> module), the code is not reloaded from the .pyc file, but instead a
> reference is retrieved from sys.modules where it was cached when the
> first import was executed.  What are you expecting to happen in that case?
> -Peter
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list