Getting a class from its name

Michael Hudson mwh at
Wed Aug 21 11:37:47 CEST 2002

Henrik Motakef <henrik.motakef at> 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:

mod = sys.modules[package]

Find the class:

klass = getattr(mod, classname)

(Inspiration from


81. In computing, turning the obvious into the useful is a living
    definition of the word "frustration".
  -- Alan Perlis,

More information about the Python-list mailing list