Dynamic Import in Python

Dynamic Import in Python

In this we will discuss how to import function or classes in dynamic way.

Scenario:

You have a flask end point which is containing the filename and function_name, when ever the user gives different filename and different function_name it needs to process the functionality

0.0.0.0:8001/test_executor/multiply?val1=45..

Errors:

@app.route('/<file_name>/<function_name>', methods=["GET"])
def dynamic_router(file_name, function_name):
    import filename
    val1 = request.args.get("val1", type=int)
    val2 = request.args.get("val2", type=int)

you will directly module not found error

ModuleNotFoundError: No module named 'filename'

The better way to avoid the no module error is we need to use the dunder ' import'

#app.py
@app.route('/<file_name>/<function_name>', methods=["GET"])
def dynamic_router(file_name, function_name):
    val1 = request.args.get("val1", type=int)
    val2 = request.args.get("val2", type=int)
    print(file_name, function_name)
    sys.path.append(config.path)
    d_import = DynamicImport(val1, val2)
    execution_result = d_import.path_setter(file_name, function_name)

final importing the code is

#app.py
class DynamicImport:

    def __init__(self, val1, val2):
        self.val1 = val1
        self.val2 = val2

    def path_setter(self, module_name, function_name):
        module = __import__(module_name)
        dynamic_func = getattr(module, function_name)
        return self.executor(dynamic_func)

    def executor(self, function_obj):
        result = function_obj(self.val1, self.val2)
        return result
#test_executor.py
def multiply(a: int, b: int):
    return a*b

Thank you..