Getting a class from its name
mwh at python.net
Wed Aug 21 11:37:47 CEST 2002
Henrik Motakef <henrik.motakef at web.de> writes:
> I guess thats an easy one, but somehow I'm blocked.
> How do I get a class given its name (or an object of this class
> Say I have the string "xml.dom.Node", how do I use it to make a Node
s = 'xml.dom.Node'
First, split off the package name:
parts = s.split('.')
package = '.'.join(parts[:-1])
classname = parts[-1]
Import the package:
mod = sys.modules[package]
Find the class:
klass = getattr(mod, classname)
(Inspiration from pickle.py:Unpickler.find_class).
81. In computing, turning the obvious into the useful is a living
definition of the word "frustration".
-- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html
More information about the Python-list