Problem with modules refering to each other

Bernhard Herzog herzog at
Sun Aug 8 11:23:37 EDT 1999

philh at (Phil Hunt) writes:

> Yes. Does Python not allow this? What's the workaround? (Originally 
> my two modules were one, with hhh containing subclasses of bak's
> classes, and bak containing code to dynamically create instances
> of hhh classes at run time, using:
>    newInstance = eval(nameOfClass + '()')
> but I wanted the code split up into two modules as it is logically 
> separate.)

A good way to implement this IMO, is to have a registry of classes in like this:

class BaseClass:
	# whatever

registry = {}

def instantiate(classname, *args, **kw):
	return apply(registry[classname], args, kw)

and in

import bak

class SubClass(bak.BaseClass):
	# whatever

bak.registry['SubClass'] = SubClass

Code that has to create instances of SubClass would then call e.g.

This way, bak doesn't have to know anything about hhh or any other
module that implements sub-classes.

Bernhard Herzog	  | Sketch, a drawing program for Unix
herzog at  |

More information about the Python-list mailing list