dakrauth
1/15/2012 - 9:04 PM

Import a callable from it's absolute path string representation

Import a callable from it's absolute path string representation

def import_callable_path(import_path):
    '''
    Import a class or function represented by an absolute Python import string.
    Useful for storing callback functions/classes from a configuration file or 
    database setting.
    
    Example:
    
        Date = import_class('datetime.date')
        MD = import_class('django.utils.datastructure.MergeDict')
        
    '''
    mod_name, attr = import_path.rsplit('.', 1)
    try:
        module = import_module(mod_name)
    except ImportError, e:
        raise ImportError('Error importing `%s`: "%s"' % (mod_name, e))
        
    try:
        return getattr(module, attr)
    except AttributeError, e:
        raise ImportError(
            'Error importing `%s` from `%s`: %s' % (attr, mod_name, e)
        )