Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a python module function dynamically?

Tags:

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 
like image 862
Pyther Avatar asked Aug 31 '10 05:08

Pyther


People also ask

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);

Can I import module in function Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


2 Answers

you want

my_function = getattr(__import__('my_apps.views'), 'my_function') 

If you happen to know the name of the function at compile time, you can shorten this to

my_function = __import__('my_apps.views').my_function 

This will load my_apps.views and then assign its my_function attribute to the local my_function.

If you are sure that you only want one function, than this is acceptable. If you want more than one attribute, you can do:

views = __import__('my_apps.views') my_function = getattr(views, 'my_function') my_other_function = getattr(views, 'my_other_function') my_attribute = getattr(views, 'my_attribute') 

as it is more readable and saves you some calls to __import__. again, if you know the names, the code can be shortened as above.

You could also do this with tools from the imp module but it's more complicated.

like image 93
aaronasterling Avatar answered Sep 25 '22 15:09

aaronasterling


Note that Python 2.7 added the importlib module, convenience wrappers for __import__() and a backport of 3.1 feature.

This module is a minor subset of what is available in the more full-featured package of the same name from Python 3.1 that provides a complete implementation of import. What is here has been provided to help ease in transitioning from 2.7 to 3.1.

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned.

like image 39
gimel Avatar answered Sep 25 '22 15:09

gimel