caught in the import web again

Charles T. Smith cts.private.yahoo at gmail.com
Mon Nov 17 15:07:35 EST 2014


On Mon, 17 Nov 2014 08:08:40 +0100, dieter wrote:

> "Charles T. Smith" <cts.private.yahoo at gmail.com> writes:
>> ...
>> 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.
> 
> Recursive imports are inherently difficult. It is best if a careful
> design avoids it (note that a cycle free dependency structure is much
> easier to handle than a cyclic one -- not only for Python).
> 
> If you think such a cycle free module structure is impossible in your
> case, then try to delay module related operations:
> 
>    *  consider local imports (imports inside a function).
>       They delay the import until the function is called rather than
>       execute it at module import time.
> 
>    *  prefer "import <module>" over "from <module> import ..."
>       This may delay the module access; perhaps (but not necessarily)
>       sufficiently such that the accessed object is already defined.
> 
> Neither of these approaches is complete - you may still get cyclic
> import dependencies and related problems. Usually, you need a careful
> module dependency design to avoid cyclic dependencies altogether.
>       
>       
>> 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.
> 
> If you put everything in a single file, then you do not get recursive
> imports (but you may still have other problems related to cyclic
> dependencies). Thus, Python's difficulties with recursive imports do not
> force you to "put everything in its own file".
> 
> If you think about it, you will recognize that cyclic dependencies are
> inherently difficult (e.g. "chicken - egg" type problems) and that the
> way Python handles cyclic import dependencies is rather natural (and
> understandable).


Well, I guess that's the definitive answer... the tips for delaying 
import are good, I'll try to leverage them.

I was hoping there would be a way to have python postpone evaluation 
similar to C's forward references.



More information about the Python-list mailing list