Reputation: 16
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?
Upvotes: 0
Views: 106
Reputation: 365717
Of course normally you don't want to import modules in the middle of an __init__
method, but a testing class is an obvious exception to that rule, so let's ignore that part and imagine you were doing this at top level:
if test_c_implementation:
import c_mymodule as mymodule
else:
import py_mymodule as mymodule
That's perfectly idiomatic. In fact, you see code like that in the stdlib and other code written by core developers.
Except in the very-common EAFP cases, where the condition is just there to avoid an exception, in which case it's more idiomatic to just do this:
try:
import lxml.etree as ET
except ImportError:
import xml.etree.cElementTree as ET
Upvotes: 1