Circular imports (again)

Michael Torrie torriem at gmail.com
Mon Aug 9 16:06:51 EDT 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 are a number of ways to avoid circular imports, in order of my own
preference:

1. Make common stuff a new module.  So if A needs something from B, and
vice versa, you must factor out the stuff and stick it in its own
module.  The fact that you have circular dependencies means that
although things are cohesive, they are way too closely coupled.

2. Instead of having A refer directly to something in B (which would
cause a circular dependency, have the caller pass in as a parameter to
the function in A, whatever is needed from B.  This could be just a
variable, complex object, or even a function or method.  Take advantage
of the fact that everything in Python is a first-class object.

3. Take advantage of Python's dynamicism.  Write an initializer function
in A that allows you to tell it about B and C.  In other words, you can
pass B and C to some method in A and have it bind B and C to local
attributes in A.   Then you can call B and C's methods just fine from A
since everything is looked up as it is called.



More information about the Python-list mailing list