Problem with modules refering to each other
Bernhard Herzog
herzog at online.de
Sun Aug 8 11:23:37 EDT 1999
philh at vision25.demon.co.uk (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
bak.py like this:
# bak.py
class BaseClass:
# whatever
pass
registry = {}
def instantiate(classname, *args, **kw):
return apply(registry[classname], args, kw)
and in hhh.py:
# hhh.py
import bak
class SubClass(bak.BaseClass):
# whatever
pass
bak.registry['SubClass'] = SubClass
Code that has to create instances of SubClass would then call e.g.
bak.instantiate('SubClass')
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 online.de | http://www.online.de/home/sketch/
More information about the Python-list
mailing list