Use of factory pattern in Python?
Nick Craig-Wood
nick at craig-wood.com
Thu Dec 7 05:30:04 EST 2006
Gabriel Genellina <gagsl-py at yahoo.com.ar> wrote:
> The basic idea is the same, but instead of a long series of
> if...elif...else you can use a central registry (a dictionary will
> do) and dispatch on the name. Classes act as their own factories.
>
> registry = {}
>
> class Base(object):
> kind = "Unknown"
> register(Base)
>
> class Gene(Base):
> kind = "gene"
> def __init__(self, *args, **kw): pass
> register(Gene)
>
> class Intron(Base):
> kind = "intron"
> def __init__(self, *args, **kw): pass
> register(Intron)
>
> def register(cls):
> registry[cls.kind] = cls
>
> def factory(kind, *args, **kw):
> return registry[kind](*args, **kw)
>
> If some arguments are always present, you can name them, you're not
> limited to use the generic *args and **kw.
If you don't want to use a register() function on each class you could
introspect like this (untested) to make the registry :-
registry = {}
for obj in sys.modules[__name__].__dict__.values():
try:
if issubclass(obj, Base):
registry[kind] = obj
except TypeError:
pass
There might be a neater way of writing the above!
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list