caught in the import web again

Charles T. Smith at
Sun Nov 16 09:53:34 CET 2014

On Sun, 16 Nov 2014 08:14:05 +0100, dieter wrote:

> "Charles T. Smith" < at> writes:
>> Now, I'm getting these errors:
>>   ImportError: cannot import name ...
>> and
>>   AttributeError: 'module' object has no attribute ...
>> (what is 'module'?)
>> Is there a way to resolve this without having to restructure my code
>> every couple of days?
>> I thought using imports of the form:
>>   from module import symbol
>> was the "right way" to avoid these hassles...
> I have not noticed your previous posts regarding import problems --
> thus, I may repeats things already said.
> Usually, Python imports are straight forward and do not lead to
> surprises. There are two exceptions: recursive imports and imports in
> separate threads. Let's look at the problem areas in turn.
> Recursive imports. In this case you have module "A" which imports module
> "B" (maybe indirectly via a sequence of intervening imports) which
> imports module "A". In this, "import" means either "import ..." or "from
> ... import ..." (it does not matter). When module "B" tries to import
> module "A", then "A" is not yet complete (as during the execution of
> "A"'s initialization code, it started to import "B" (maybe indirectly)
> and the following initialization code has not yet been executed). As a
> consequence, you may get "AttributeError" (or "ImportError") when you
> try to access things from "A". To avoid problems like this, try to avoid
> recursive imports. One way to do this, are local imports -- i.e. imports
> inside a function. This way, the import happens when the functions is
> called which (hopefully) happens after module initialization.

Yes, we're talking about recursive imports here.  It's a complex, object-
oriented system with big classes and little classes that are strongly 
interrelated.  I can get the imports configured properly so everything 
works but if I make a little change to the code, then suddenly all my 
imports are broken and I must painstakingly go through the whole 
structure, reorganizing them.

Are others equally frustrated by this or is there a trick or principle 
that I'm missing.  At this point, I guess the way I'll have to proceed is 
to put every class in its own file, no matter how small.  Hopefully that 
takes care of the problem.

I compared perl's object-oriented philosophy with python's and didn't 
like how perl *requires* you to put everything into its own file.  Now it 
looks like python does, too, implicitly.


More information about the Python-list mailing list