How to organize code for conversion between different classes? (avoiding cyclic dependencies)

Peng Yu pengyu.ut at gmail.com
Thu Oct 15 17:02:34 CEST 2009


Suppose I have classes 'A',  'B',  'C',  'D'. The definition of these
classes are long enough so that I have to put each class in a separate
module 'mA', 'mB', 'mC', 'mD', which are in packages 'pA', 'pB', 'pC',
'pD', respectively. And there were no need to have conversion
functions between these classes.

As my program evolves, I need to have a conversion function between
any pair of classes. I could define the conversion functions as member
methods like the following. But if I do this for the classes B, C, D,
I would end up with cyclic dependencies, which should be avoid.

################
import pB.mB
import pC.mC
import pD.mD

class A:
  ...
  def convert_to_B():
     ....

  def convert_to_C():
     ....

  def convert_to_D():
     ....
################

Another choice is that I can put the conversion functions in some
modules and import 'mA', 'mB', 'mC', 'mD' when needed. However, since
mA, mB, mC, mD are in different packages, I'm not sure where to put
the new modules that have the conversion functions.

I'm wondering how this case shall be handled. Could somebody give some hint?



More information about the Python-list mailing list