caught in the import web again

dieter dieter at handshake.de
Sun Nov 16 02:14:05 EST 2014


"Charles T. Smith" <cts.private.yahoo at gmail.com> 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.

Imports and threads. The import machinery changes global data structures
(e.g. "sys.modules"). To protect those changes, it uses a lock, held
while an import is in progress. When, during an import, a separate
thread tries to import something, it blocks - waiting for the import
lock to be released. In case, the importing thread waits on this
thread, then the system deadlocks.
To avoid this: do not start threads during imports.





More information about the Python-list mailing list