Newbie - circular import problem

Duncan Booth me at privacy.net
Tue Feb 24 08:17:25 EST 2004


stuart_white_ at hotmail.com (sw) wrote in
news:db1b46bd.0402240215.4d7ea76a at posting.google.com: 

> Could someone explain what is going wrong here? I'm still getting up
> to speed with python, but, to me, this looks like the import of b is
> occuring before ClassA has been defined. Is that right? How can I
> correct this, apart from amalgamating the two into a single file?
> 

There are some posts giving solutions to this, but I'm not sure that any of 
them really explain the problem.

Remember that import statements and class/def statements, like almost 
everything in Python are executed at runtime. Very little (apart from 
compiling) happens at compile time.

When an import statement is executed it:

    	finds the module and compiles or loads it as appropriate.

     then, if the module code has already started executing it simply 
returns the module.

     otherwise, it executes the module code and then returns the module.

So if b is imported first, it imports a, a tries to import b and simply 
gets back a reference to b as it currently exists: i.e. without the class 
it will later define. If a is imported first then it happens the other way 
round, b gets a reference to an incompletely executed module a.

The simplest way to avoid this problem is to remove your 'import b' from 
module 'a'. Since in the code you cut this import isn't used it won't be a 
problem. If you really have stuff in 'a' that needs to get at 'b' then make 
sure that all references from 'a' to 'b' can't execute until after 'b' has 
finished importing. References to 'b.something' from inside functions 
defined by 'a' will be fine, but you can't refer to 'b.something' from 
inside the body (and outside the methods) of ClassA.



More information about the Python-list mailing list