mercredi 7 février 2018

Import different module for functions given argument

Suppose I have two files. In the first file, the main function takes input usr_input and then calls a function myfun in the second file. The functions in the second file imports a module according to usr_input and call its methods. (Of course the imported classes have the same interface)

Currently I am passing usr_input as a parameter and use importlib, as shown in the simplified code:

# A.py
class A:
    def foo(self):
        print('This is class A')

# B.py
class B:
    def foo(self):
        print('This is class B')

# main.py
from test_module.fun import *
if __name__ == '__main__':
    usr_input = 'A' # or 'B'
    myfun(usr_input)

# fun.py
import importlib
def myfun(module_name):
    mn = importlib.import_module('test_module.'+module_name)
    mnc = getattr(mn, module_name)
    mnc().foo()

However using importlib in functions has caused problems and must be replaced (module should be imported before function is called, typically import at the beginning of file). How should I change the design (rather not to import all possible classes: A, B...)?

PS: reading the module name from saved external file does not work because myfun is initialized before value of it is known.

Aucun commentaire:

Enregistrer un commentaire