Instantiate arbitrary classes at run time

Mike Fletcher mfletch at
Thu Mar 30 17:33:59 CEST 2000

Here's a simple little function that does the basic work...

import string
def getModule( modulename ):
	return __import__(

And an example of using it to get your arbitrary class (in this case
"Pickler" in the module "pickle")...

>>> import getmodule
>>> getmodule.getModule( 'pickle' )
<module 'pickle' from 'D:\bin\lang\Python\Lib\pickle.pyc'>
>>> getattr( getmodule.getModule( 'pickle' ), "Pickler")
<class pickle.Pickler at 1f34310>
>>> getattr( getmodule.getModule( 'pickle' ), "Pickler")( open(
<pickle.Pickler instance at 1fb1ba0>

Note: open(...) is just getting the one argument to the class, should have
used a class with a simpler instantiation signature :) .


-----Original Message-----
From: jiml at [mailto:jiml at]
Sent: Thursday, March 30, 2000 10:07 AM
To: python-list at
Subject: Instantiate arbitrary classes at run time

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.

Sent via
Before you buy.

More information about the Python-list mailing list