How can I import a python module function dynamically?

后端 未结 4 1794
春和景丽
春和景丽 2021-02-01 18:31

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

4条回答
  •  长情又很酷
    2021-02-01 19:17

    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.

提交回复
热议问题