Instantiate arbitrary classes at run time

Mike Fletcher mfletch at tpresence.com
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__(
		modulename,
		{},
		{},
		string.split(modulename,'.')
	)


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(
'c:\\temp\\simpletest.txt','w'))
<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 :) .

HTH,
Mike

-----Original Message-----
From: jiml at longson.com [mailto:jiml at longson.com]
Sent: Thursday, March 30, 2000 10:07 AM
To: python-list at python.org
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 Deja.com http://www.deja.com/
Before you buy.
-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list