I'm working on a django project that serves multiple sites; depending on the site I want to import different functionality from a different module; how do I import a module in Python if I have the name of its package and the module name itself as a string?
in Python generally, you can use __import__
builtin function or imp
module features:
>>> sys1 = __import__("sys")
>>> import imp
>>> sys2 = imp.load_module("sys2", *imp.find_module("sys"))
>>> import sys
>>> sys is sys1 is sys2
True
Django has its own import function to get an objet from a string. From documentation :
django.utils.module_loading
Functions for working with Python modules.
import_string(dotted_path)
Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises ImportError if the import failed. For example:
from django.utils.module_loading import import_string ValidationError = import_string('django.core.exceptions.ValidationError')
is equivalent to:
from django.core.exceptions import ValidationError
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.