FAQ 1.7.3 : How can I have modules that mutually import each other

david.tolpin at gmail.com david.tolpin at gmail.com
Mon Mar 21 08:52:55 EST 2005


> Needs??? Sorry to be blunt, but this is an intrinsically ludicrous
> concept, in *any* language. The whole idea of modules is (wait for
it)
> "modularity". "A imports B which imports A" is an utter nonsense.
>

There is such a thing called 'recursion'. Self-recursion is when
function x calls itself to execute the same action on a partial result
of its previous invocation. This technique is a natural expression of
what such ugly constructs as for and while  are for in some programming
languages. Indirect recusion is when function x calls y, and function y
calls x. It is often happens in state automata.

A static equivalent of indirect recursion is dependencies between
declarations, when declaration x depends on y, and declaration y
depends on x. Imagine a design
of a literate programming environment, where both documentation and
text are structured, and either can contain the other. A natural design
for that is to have two modules, one implementing the parser for
documentation, the other implementing the parser for code, each
referencing the other so that both parsers can call each other when
they need to switch context.

In a well-designed programming language, circular intermodule
dependencies are normal, because this is a natural high-level
abstraction to express such relations. Because of primitive
implementation of modular system in Python, circular dependencies are
not possible, and things which are normally done automatically in a
higher-level language, need to be coded manually in Python.

In particular, to bypass this deficiency of Python for a problem
similar to one described above, one has to define base classes for each
of the two parsers, and make the implementations depend on the other
implementation's base class, not on itself, thus splitting the
interface and the implementation where it is not only unnecessary but
outright wrong if clean design is taken into consideration.

I'd wish a cleaner and more consistent implementation of packages
existed in Python; but unfortunately too many things in current Python
are far from being on the level a modern programming language (such as
Common Lisp, for example) demands.

David Tolpin
http://davidashen.net/




More information about the Python-list mailing list