Factory function to generate a named class

Miki Tebeka tebeka at cs.bgu.ac.il
Tue Sep 30 07:09:32 EDT 2003


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




More information about the Python-list mailing list