I have a seemingly simple Python code design problem that I have not found any elegant solution to. I have a set of modules (two in the example below) that define functions of the same name that compute the same thing but using different algorithms:
algorithm_a.py:
def compute_1(x):
# do some computation
return (x+1.)**2
def compute_2(x):
# do some other computation
# etc
algorithm_b.py:
def compute_1(x):
# do same computation in another way
return x*x + 2.0*x + 1.0
def compute_2(x):
# do some other computation in another way
# etc
Both modules have approximately 10 functions, but the number might grow in the future.
In a third module, I have functions defined that are not aware of the details of how the computation is performed, i.e. they only care about getting the correct answer. The interface to the user is provided by a class. All in all, the third module looks similar to:
simulation.py:
import XXX as algo #????
def do_computation_1(x):
v1 = algo.compute_1(x)
v2 = algo.compute_2(x)
# Do some computations using v1, v2
return result
def do_computation_2(x):
return algo.compute_2(x)
# etc etc
class Simulation(object):
def __init__(self, method):
# Do some magic here so that
# if method == "A":
# algo = algorithm_a
# if method == "B"
# algo = algorithm_b
def run(self, x):
do_computation_1(x)
do_computation_2(x)
How can I get the correct module loaded and applied in do_computation() to depend on the method parameter supplied to the class?
Note that the do_computation functions need to remain outside of the Simulation class.
CONCLUSION: The comment by @BrenBarn below summarises well the available options. Thanks all for the great help!