Dynamically import a method in a file, from a string

Lakshman Prasad picture Lakshman Prasad · Jan 9, 2012 · Viewed 87.3k times · Source

I have a string, say: abc.def.ghi.jkl.myfile.mymethod. How do I dynamically import mymethod?

Here is how I went about it:

def get_method_from_file(full_path):
    if len(full_path) == 1:
        return map(__import__,[full_path[0]])[0]
    return getattr(get_method_from_file(full_path[:-1]),full_path[-1])


if __name__=='__main__':
    print get_method_from_file('abc.def.ghi.jkl.myfile.mymethod'.split('.'))

I am wondering if the importing individual modules is required at all.

Edit: I am using Python version 2.6.5.

Answer

frm picture frm · Jan 9, 2012

From Python 2.7 you can use the importlib.import_module() function. You can import a module and access an object defined within it with the following code:

from importlib import import_module

p, m = name.rsplit('.', 1)

mod = import_module(p)
met = getattr(mod, m)

met()