Converting a string into a function (or class) object

Problem

It's a common idiom to refer to a function (or class) using the "module.submodule.func_name" string format. This is good when you want to create a settings file, and you don't want to have to deal with importing models and functions there. Lots of python software uses this idiom, for example, lots of Django Settings use this.

Python has an __import__ function (documentation here), which is the same as doing import $SOMETHING, however if module.submodule.func_name is a function (or a class), it is not a module, and hence it cannot be imported itself. You would have to do from module.submodule import func_name, and it's not obvious from the __import__ builtin function how to do that.

Another problem, as the python documention says, if you use __import__('module.submodule'), you will get module, and not module.submodule returned.

Solution

Here's a little function that will take a string like above and return the function itself.

def import_func_from_string(string_name):
    """Given a string like 'module.submodule.func_name' which refers to a function, return that function so it can be called"""
    # Split the string_name into 2, the module that it's in, and func_name, the function itself
    mod_name, func_name = string_name.rsplit(".", 1)

    mod = __import__(mod_name)
    # ``__import__`` only gives us the top level module, i.e. ``module``, so 'walk down the tree' getattr'ing each submodule.
    # from http://docs.python.org/faq/programming.html?highlight=importlib#import-x-y-z-returns-module-x-how-do-i-get-z
    for i in mod_name.split(".")[1:]:
        mod = getattr(mod, i)

    # Now that we have a reference to ``module.submodule``, ``func_name`` is available as an attribute to that, so return it.
    return getattr(mod, func_name)