Factory function to generate a named class

Jeff Epler jepler at unpythonic.net
Tue Sep 23 13:54:32 CEST 2003

Populate a dict with a mapping from class names to class objects:

d = {}
def register(cls):
    d[cls.__name__] = cls

def factory(clsname, model):
        factory = d[clsname]
    except KeyError:
        raise TypeError, "Class %s not registered" % clsname

    return factory(model)

class ViewController: pass

If you absolutely want this to be automatic, a metaclass trick can
probably be played to do it.  Something like:
    class FactoryMeta(type):
        def __init__(cls, name, bases, dict):
            super(FactoryMeta, cls).__init__(name, bases, dict)

    class Factory(object):
        __metaclass__ = "FactoryMeta"
    del d["Factory"] # Unregister this "abstract" class

All code is untested.


More information about the Python-list mailing list