How can I import a python module function dynamically?

Viewed 20117

Assuming my_function() is located in my_apps.views I would like to import my_function dynamically without using something like exec or eval.

Is there anyway to accomplish this. I'm looking to do something similar to:

my_function = import_func("my_apps.views.my_function")

my_function()
   ... code is executed
6 Answers

Use the standard library pkg_resources

from pkg_resources import EntryPoint
my_function  = EntryPoint.parse("my_function=my_apps.views:my_function").load(require=False)

We have four cases separated by the fact whether the module and/or the function fixed or not:

  1. module name is a fixed string, function name is a fixed string:
    my_function = __import__('my_apps.views', fromlist=['my_function'].my_function
    
    (altough in this case it is much more simple to use from my_app.views import my_function)
  2. module name is a fixed string, function name is variable:
    function_name = ...
    .
    .
    .
    my_function = getattr(__import__('my_apps.views', fromlist=[function_name]),
                          function_name)
    
  3. module name is variable, function name is fixed string:
    module_name = ...
    .
    .
    .
    my_function = __import__(module_name, fromlist=['my_function']).my_function
    
  4. module name is variable, function name is variable:
    module_name = ...
    .
    .
    .
    function_name = ...
    .
    .
    .
    my_function = getattr(__import__(module_name, fromlist=[function_name]),
                          function_name)
    

Note: For an empty list (that's the default value) as __import__ keyword argument fromlist not the module, but the package root is returned. For all non-empty lists the actual module returned.

Sources and further information:

Related