Does python always need to compile ENTIRE program before it c an start to run it???

Peter Hansen peter at engcorp.com
Tue Nov 4 08:06:23 EST 2003


"Daniel P. M. Silva" wrote:
> 
> On Mon, 03 Nov 2003 18:34:33 -0500, Ellinghaus, Lance wrote:
> > If I remember correctly, Yes.
> > Python will import each module, compile if necessary, and then execute it.
> > This might cause additional modules to be compiled, loaded, etc.. But Python
> > will not import a module more than one time. Each additional time the import
> > is called for the same module, Python just binds a new reference into the
> > namespace.
> 
> What about this?
> 
> [/tmp] > cat > a.py
> import b
> print "module A loaded"
> [/tmp] > cat > b.py
> import a
> print "module B loaded"
> [/tmp] > python a.py
> module A loaded
> module B loaded
> module A loaded

Special case, with a circular reference involving the __main__ script.
Basically the problem is that the script that is invoked from the command
line is not imported in the usual fashion, but is executed as the module
__main__ (check sys.modules to verify this if you wish).  As a result,
if an imported module such as B tries to import a module called A,
this module is not found in sys.modules already so the importing
proceeds again.  If module B had used "import __main__" this would
not have happened.

Call this a small lesson in one of the problems circular references
can cause.  Easiest to avoid them. :-)

-Peter




More information about the Python-list mailing list