I want to import modules dynamically in my class depending on some conditions.
class Test(object):
def __init__ (self,condition):
if condition:
import module1 as mymodule
else:
import module2 as mymodule
self.mymodule = mymodule
def doTest(self):
self.mymodule.doMyTest
where module1 and module2 implement doMyTest in different way.
Calling it as
mytest1 = Test(true) # Use module1
mytest2.doTest()
mytest2 = Test(false) # Use module2
mytest2.doTest()
This works but is there possibly a more idiomatic way? Are there any possible problems?
module1will only be executed the first time youimport module1 as mymodule; after that, each subsequentimport module1 as mymoduleis effectively equivalent tomymodule = sys.modules['module1']. So, it might be less misleading to make that explicit: importmodule1andmodule2once, then just haveif…: self.mymodule = module1… else: self.mymodule = module2.