Circular imports (again)

Frank Millman frank at chagford.com
Mon Aug 9 09:19:30 EDT 2010


Hi all

I know the problems related to circular imports, and I know some of the 
techniques to get around them. However, I find that I bump my head into them 
from time to time, which means, I guess, that I have not fully understood 
how to organise my code so that I avoid them in the first place.

It has just happened again. I have organised my code into three modules, 
each representing a fairly cohesive functional area of the overall 
application. However, there really are times when Module A wants to invoke 
something from Module B, ditto for B and C, and ditto for C and A.

I can think of two workarounds. One is to place the import statement inside 
the function that actually requires it. It is therefore not executed when 
the module itself is imported, thereby avoiding the problem. It works, but 
breaks the convention that all imports should be declared at the top of the 
program.

A second solution is to avoid invoking the other modules directly, but 
rather use global Queue.Queues to pass requests from one module to another. 
Again, it works, but adds complication, especially if the 'invoker' needs to 
get a return value.

So I think my main question is, is this a symptom of a flaw in my approach, 
or is this something that all programmers bump into from time to time?

If the former, I can expand on my current requirement if anyone would like 
to suggest a better approach. If the latter, is either of the above 
solutions preferred, or are there other techniques to get around the 
problem.

Any suggestions will be appreciated.

Thanks

Frank Millman





More information about the Python-list mailing list