From turbogears.util:
def load_class(dottedpath):
"""Load a class from a module in dotted-path notation.
E.g.: load_class("package.module.class").
Based on recipe 16.3 from Python Cookbook, 2ed., by Alex Martelli,
Anna Martelli Ravenscroft, and David Ascher (O'Reilly Media, 2005)
"""
assert dottedpath is not None, "dottedpath must not be None"
splitted_path = dottedpath.split('.')
modulename = '.'.join(splitted_path[:-1])
classname = splitted_path[-1]
try:
try:
module = __import__(modulename, globals(), locals(), [classname])
except ValueError: # Py < 2.5
if not modulename:
module = __import__(__name__.split('.')[0],
globals(), locals(), [classname])
except ImportError:
# properly log the exception information and return None
# to tell caller we did not succeed
logging.exception('tg.utils: Could not import %s'
' because an exception occurred', dottedpath)
return None
try:
return getattr(module, classname)
except AttributeError:
logging.exception('tg.utils: Could not import %s'
' because the class was not found', dottedpath)
return None
use it like this:
cls = load_class('package.module.class')
obj = cls(...)