[Tutor] reciprocal import

Kent Johnson kent37 at tds.net
Tue Dec 16 21:38:19 CET 2008


On Tue, Dec 16, 2008 at 3:06 PM, spir <denis.spir at free.fr> wrote:
> Is it legal or possible  at all for two modules to import each other? I
> tried several ways and had several kinds of error messages. Usually
> "can't import...".

It is possible but better to avoid it, perhaps by putting common
functionality into a third module.

The problem is that 'import' is an executable statement and modules
are executed when they are imported. If A.py imports B.py and
vice-versa, then A is not completely defined when B is loaded, and
access to names in A may fail. For example, this will not work:

# A.py
import B

def hello():
    print 'hello'

# B.py
import A
A.hello()


Running A.py will get a NameError in B because A.hello doesn't exist
at the point where B is loaded.

If neither A or B tries to access the contents of the other at load
time you are probably OK, but still it is a bad design and better to
find another solution.

Kent


More information about the Tutor mailing list