We have a file with a few different classes which all do the same thing but in different ways. Each of these classes have a couple of imports from external packages.
Our run file then uses the configs (parsed as a dictionary) to find which methodology the user would like i.e. which class to use.
Now, we don't want to force the user to get all the packages if they are only going to use one methodology. So we would like a way of handling conditional imports.
I have seen that some people handle this with a simple:
try:
import module
except ImportError:
try:
import other_module
except ImportError:
raise
However, we have a fair few of these imports and daisy-chaining them like this is hard to maintain and clumsy.
I could write something which simply loops through a list of modules until one (or more) imports successfully, but then where should this logic go? In the file containing the classes, or in the run file which imports those classes?
Finally, we could just add the imports to the classes' namespaces:
class EngineOne:
import module
def methodology_one(self):
self.module.function()
class EngineTwo:
import other_module
def methodology_two(self):
self.other_module.function()
This however seems very non-standard and I can't find any real-world examples where people have done this. self.module.function()
also feels very odd even if it makes sense to have the imports as class variables.
I've had a brief look through some common data science packages I have installed but can't find any where this sort of thing is used.
I have found a few stackoverflow questions which have briefly mentioned conditional imports such as this one and this one, but none where there are concrete examples which well-describe our case.
Thanks for any help.