dynamic class/module use? (like Java's forName)

Christopher T King squirrel at WPI.EDU
Mon Jul 19 09:20:07 EDT 2004


On Sat, 17 Jul 2004, Alex Hunsley wrote:

> classIWantToInstantiate = "packagenamehere.classNameHere"
> 
> anInstanceOfThatClass = makeNewClassFromString(classIWantToInstantiate, 
> parameters[])
> 
> # now anInstanceOfThatClass refers to an instantied
> # packagenamehere.classNameHere object!

getattr is probably the best way to go about this:

packagename,classname = classIWantToInstantiate.split('.')
myclass = getattr(locals()[packagename], classname)

Or, if you want to support nested classes:

classnames = classIWantToInstantiate.split('.')
myclass = locals()[classnames[0]]
for classname in classnames[1:]:
    myclass = getattr(myclass, classname)

Then you can just instantiate the class with myclass().

(Question for those in the know: why isn't there a way you can reference 
the current module, i.e. so getattr(current_module,something) would be 
equivalent to locals()[something]?)




More information about the Python-list mailing list