Dynamically import a method in a file, from a string Dynamically import a method in a file, from a string python python

Dynamically import a method in a file, from a string


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_modulep, m = name.rsplit('.', 1)mod = import_module(p)met = getattr(mod, m)met()


You don't need to import the individual modules. It is enough to import the module you want to import a name from and provide the fromlist argument:

def import_from(module, name):    module = __import__(module, fromlist=[name])    return getattr(module, name)

For your example abc.def.ghi.jkl.myfile.mymethod, call this function as

import_from("abc.def.ghi.jkl.myfile", "mymethod")

(Note that module-level functions are called functions in Python, not methods.)

For such a simple task, there is no advantage in using the importlib module.


For Python < 2.7 the builtin method __ import__ can be used:

__import__('abc.def.ghi.jkl.myfile.mymethod', fromlist=[''])

For Python >= 2.7 or 3.1 the convenient method importlib.import_module has been added. Just import your module like this:

importlib.import_module('abc.def.ghi.jkl.myfile.mymethod')

Update: Updated version according to comments (I must admit I didn't read the string to be imported till the end and I missed the fact that a method of a module should be imported and not a module itself):

Python < 2.7 :

mymethod = getattr(__import__("abc.def.ghi.jkl.myfile", fromlist=["mymethod"]))

Python >= 2.7:

mymethod = getattr(importlib.import_module("abc.def.ghi.jkl.myfile"), "mymethod")