Getting a class from its name
Michael Hudson
mwh at python.net
Wed Aug 21 05:37:47 EDT 2002
Henrik Motakef <henrik.motakef at web.de> writes:
> Hi,
>
> 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
> ultimatly)?
>
> Say I have the string "xml.dom.Node", how do I use it to make a Node
> object?
s = 'xml.dom.Node'
First, split off the package name:
parts = s.split('.')
package = '.'.join(parts[:-1])
classname = parts[-1]
Import the package:
__import__(package)
mod = sys.modules[package]
Find the class:
klass = getattr(mod, classname)
(Inspiration from pickle.py:Unpickler.find_class).
HTH,
M.
--
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
mailing list