Circular imports (again)

Carl Banks pavlovevidence at gmail.com
Mon Aug 9 20:51:47 CEST 2010


On Aug 9, 6:19 am, "Frank Millman" <fr... at chagford.com> wrote:
> 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.

There's a dozen reasons why circular imports can go wrong.  Can you
describe the problem you're having getting them to work?  If there's a
traceback when you try to do it, cut-and-paste the traceback and
relevant code here.  If it's running, but you are not getting the
behavior you expect, tell us what you expected to happen and what
actually did.


[snip]
> 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?

I consider the need to resort to circular imports a red flag, not a
manifest error.  You say you are organizing the modules
"functionally".  I find that when I do that, I will occasionally get
circular references, so I can believe you.  I also find that in most
such cases, reorganizing the modules according to "dependencies", so
as to remove the circular import, makes it more confusing.  Sometimes
organizing by function makes more sense than organizing by dependency,
and it's better to live with circular imports than to use a less-
sensical organization.


Carl Banks



More information about the Python-list mailing list