py files includings each others

John Roth newsgroups at
Wed Mar 24 02:46:23 CET 2004

"Nicolas Bouillon" <bouil at> wrote in message
news:AL48c.32121$zm5.13267 at
> Hi
> I have a big problem while including file.
> I have more that twenty classes, with one py file per class (more clear
> & clean), and the following test case illustrate well my problem. I
> facts, files including each other before the name of the classes seems
> to be defined, so python fails...
> Can you help me to resolve that ?

Circular import dependencies don't work the way a
lot of people think they do.

What happens is very simple, but you have to trace
the actual execution to see it.

When you hit an import, the module is imported
and initialized, and then the loading of the first module
continues. This is obvious, right? What's not obvious
is that Python puts a reference to the new module in
it's internal import table *before* the module has
been completely initialized.

Now, if the second module contains an import of the
first module, Python sees the module in the import
table and creates a reference to it, and then returns
immediately. The second module then sees the ***partially loaded***
version of the first module. Nothing past the import
statement has been loaded yet.

Note that it has to do this: otherwise it would either
deadlock on a partially loaded module, or it would
have to fail the second import.

The only time this matters if there is something in the
second module that depends on the unloaded part
of the first module *while it is being loaded*. For
the most part, this is subclasses looking for their
parent class definitions.

There are a number of ways around this. The
"best" solution is, of course, to eliminate the
circular dependency. Another solution is to
move the import statements around. Another
is to put more than one class in a module.
If you can't eliminate the logical dependency,
then do a two phase initialization so that you
can eliminate the circular dependency at load
time, and do the rest of the linkages after the
program is loaded.

Hope this helps.

John Roth

More information about the Python-list mailing list