This Python function, named function_importer
, is designed to dynamically import a function from a specified module within a given project directory. It performs the import in a way that allows the user to reload the module and access the desired function.
Here's a breakdown of what the function does:
-
Import necessary modules:
import importlib
: Used to dynamically import the module.import sys
: Provides access to Python interpreter settings and functions.import os
: Provides access to operating system functionalities.from importlib import import_module
: Importing theimport_module
function fromimportlib
module.
-
Function definition: The function
function_importer
takes three parameters:project_name
: The name of the project directory where the module is located.module_name
: The name of the module (including its path) from which the function should be imported.function_name
: The name of the function to be imported.
-
Determine the absolute project directory: The function computes the absolute path to the project directory by navigating upwards from the current file's directory and then descending into the specified
project_name
directory. -
Modify the
sys.path
to include the project directory: Thesys.path
is a list of directories Python uses to search for modules. By inserting theproject_dir
at the second position in this list, Python will look in this directory when attempting to import modules. -
Splitting the module name: The
module_name
parameter is split into two parts: the parent module path (p
) and the actual module name (m
). This is done using thersplit()
method with a.
delimiter, allowing the function to import modules from subpackages. -
Import the module: The
importlib.import_module()
function is used to dynamically import the parent module (p
). This will load the module into memory, but if the module has already been imported previously,importlib.reload()
is called to ensure that the latest version of the module is used. -
Attempt to get the loaded function: The function tries to access the desired function (
function_name
) within the loaded module. If it exists, the function is returned. If the function does not exist, anAttributeError
will be raised. -
Return the function: If everything goes well, the function is successfully imported and returned to the caller.
import importlib
import sys
import os
from importlib import import_module
def function_importer(project_name, module_name, function_name):
project_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__),
'..', '..', '..', '{}'.format(
project_name)))
sys.path.insert(1, project_dir)
p, m = module_name.rsplit('.', 1)
module = importlib.import_module(p)
importlib.reload(module)
try:
loaded_module = getattr(module, m)
except AttributeError:
raise('Add from .{} import * into {}.views.py'.format(
m, p))
funct = getattr(loaded_module, function_name)
return funct