Python – Dynamically import a callable given the full module path

importintrospectionmodulepython

>>> import_path('os.path.join')
<function join at 0x22d4050>

What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package.

Best Answer

This seems to be what you want:

def import_path(name):
    modname, _, attr = name.rpartition('.')
    if not modname:
        # name was just a single module name
        return __import__(attr)
    m = __import__(modname, fromlist=[attr])
    return getattr(m, attr)

To make it work with Python 2.5 and earlier, where __import__ doesn't take keyword arguments, you will need to use:

m = __import__(modname, {}, globals(), [attr])