Factory function to generate a named class

D

Derek Fountain

I have a situation where I have, in a string, the name of a class I want an
instance of. I've written a factory function to generate the class for me:

def controllerFactory( controllerRequired, model ):
if controllerRequired == "ViewController":
return ViewController( model )
elif controllerRequired == "FontController":
return FontController( model )
elif controllerRequired == "ColourController":
return ColourController( model )
else:
raise TypeError

Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?
 
P

Peter Otten

Derek said:
Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?

class FontController:
def __init__(self, model):
pass

class Model:
pass

def getClass(classname, modulename="__main__"):
return getattr(__import__(modulename, globals(), locals(), [classname]),
classname)

model = getClass("Model")()
print getClass("FontController")(model)

Should be fairly self-explanatory :)

Peter
 
J

Jeff Epler

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

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

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

return factory(model)

class ViewController: pass
register(ViewController)

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)
register(cls)

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

All code is untested.

Jeff
 
M

Miki Tebeka

Hello Derek,
Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?

If you don't mind using "eval" then:

from types import ClassType
def gen_class(name):
try:
c = eval(name)
if type(c) != ClassType:
return None
return c
except NameError:
return None

HTH.
Miki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top