Instantiate arbitrary classes at run time
Robert Cragie
rcc at jennic.com
Thu Mar 30 12:03:39 EST 2000
<jiml at longson.com> wrote in message news:8bvqhr$upu$1 at nnrp1.deja.com...
> I am trying to create an instance of an arbitrary class at run time.
> I can load the class easily enough by
> target = 'arbitrary_class_name'
> command = "from " + str(target) + " import " + str(target)
> exec( command )
> But can't figure out how to create an instance of the class without
> using the class name
> instance = arbitrary_class_name()
> works fine, but I need to be able to create that instance based on the
> string stored in target
> In Java, I would code something like
> instance = Class.forName( target );
> and that would produce the same result as
> instace = new arbitrary_class_name( )
> I suspect the same capability exists in Python, but I haven't figured
> out how to find it in the documentation.
Something like this should work:
class Myclass:
def __init__(self, data):
print data
target = 'Myclass'
try:
instance = locals()[target]('Howdy')
except KeyError:
print 'Class doesn't exist'
locals() returns the local symbol table dictionary. This should also include
globally scoped classes, but I'm not entirely sure.
Note I'm a Python 'newbie', so if any expert thinks this is flawed, please
post. BTW, I think Python is great!
Robert Cragie
More information about the Python-list
mailing list