Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Module dynamically

I have some modules like this:

    Drivers/
        a.py
        b.py
        c.py

Now I want to call them on the basis of a variable value. let us consider driver is the variable from where I will get the variable name.

    if driver=='a':
        #then call the driver a and execute.
        a.somefunction()
    if driver=='b':
        #then call the driver b and execute

I know the value we get from the driver in if statement is a string type value and in the if statement we have to call a module. is there any way to convert it.??

like image 912
Raju Ahmed Shetu Avatar asked Jul 31 '26 08:07

Raju Ahmed Shetu


2 Answers

If your "Drivers/" directory in the searchpath of python, simply import the module and call the function:

import importlib
module = importlib.import_module(driver)
module.some_function()
like image 93
Daniel Avatar answered Aug 01 '26 22:08

Daniel


If the modules are in the same level(exactly your case), just

module = __import__(driver)
module.somefunction()

driver can be string such as 'a', 'b', or 'c'. If the module does not exist, ImportError is raised.

like image 43
emeth Avatar answered Aug 01 '26 20:08

emeth