[Tutor] reciprocal import

spir denis.spir at free.fr
Tue Dec 16 23:18:25 CET 2008


Steve & Kent:
Actually, I have 2 main modules that work together to achieve the task.
In the first one is defined a set of objects that outline the creation
of objects which classes & subclasses are in the second module. Only for
clarity I need two modules.
A third one copes with exceptions -- so it needs to be referenced in
both other modules. But, in order to provide the user meaning- and
help-ful information, I need to access some elements from the module
that launched the exception.
Actually, the whole of it forms a unity and can be put in a single file
-- but isn't this true for any application?

Denis


Le mardi 16 décembre 2008 à 15:38 -0500, Kent Johnson a écrit :
> 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