circular import Module

Magnus Lycka lycka at carmen.se
Tue Jun 14 11:05:58 CEST 2005


Greg Ewing wrote:
> Magnus Lycka wrote:
> 
>> Due to the cycle, you can never use file1 without
>> file2 or vice versa. Why do you then want it to be
>> two different modules instead of one?
> 
> Perhaps because it would then be too big and
> unwieldy to maintain?
> 
> Sometimes there are legitimate reasons for
> mutually-dependent modules.

Agreed, but I think it's important to think about
the design if a chunk of code gets that big. Most
of the time, things can be organized differently,
and there will be maintenance gains from this. If
you have mutual dependenices between two modules,
they still have to be maintained as a unit. You
can't disregard one when you modify the other. To
achieve looser (and prefereably not mutual)
dependencies between separate modules both makes
it easier to maintain the modules and more likely
that we will be able to reuse them in other contexts.

Sure, there simple are tricks you can use to get away
with mutual import dependencies, but if I ran into a
mutual dependency between two Python modules, I would
first think about their design and try to resolve this
dependency issue. I probably wouldn't use a trick such
as import in a local scope unless I was in a hurry and
needed a quick fix while I was considering a proper
design. (I might then be lazy and not resolve the
design problem, but it would continue to disturb me...)

Composition and inheritance might be used to break
out parts of code that doesn't have dependencies to
the rest of the code. There are all sorts of design
pattern that can resolve mutual dependencies. I often
use callbacks to get away from mutual dependencies.

E.g.

class Adder:
     def __init__(self, x, y, callback):
         self.x = x
         self.y = y
         self.callback = callback

     def calc(self):
         result = self.x + self.y
         self.callback(result)

class Manager:
     def add(self, x, y):
         b = B(x, y, self.show)
         b.calc()

     def show(self, value):
         print value

This is a silly example of course. Adder.calc could simply
have returned the result, but I don't have time to construct
anything elaborate now. The point I want to show is that
by passing in a callable from Manager to Adder, Adder
instances can call certain methods in particular Manager
instanes without any dependencies to the module where Manager
lives. It just needs to know what kind of parameters it should
supply to the callable it was passed.

Martin Fowler's book Refactoring shows a lot of examples
that are useful when code grows and needs to be divided
into smaller chunks. His examples and ideas revolve around
Java and C++ though, and it's often much simpler in Python.



More information about the Python-list mailing list