I am doing an overhaul of my code that I wrote when I was a much bigger Python beginner than now and therefore it is ugly, stinky and not optimised (still gets the job done, but it takes ages and changing anything is a big no-no). The code is a partial differential equation solver. What it does is that it initialises a 2D numpy array of space points and solves the equations in each of the points, in parallel (so most of its functions take the array of points as and argument and return an array).
Some of the code settings that the user provides (in another .py file that just stores these settings) influence the logic of the calculation and this is where my question comes.
Let’s say that the user has indicated that some boolean switch, switch_1 = True.
And let’s say that in that case I have some function my_function_1() that does some of the calculation (in all of the points) that has to be called during the solution.
The function may consist of ~100 steps of the calculation and returns an array that has to be passed in another function etc.
If switch_1 == False, the calculation changes slightly (because conditions in some of the array’s points change). Therefore another function my_function_2() has to be called.
My problem is that my_function_1() and my_function_2() differ lets say from line 90 of the function
to line 100 (only 10 lines are different really).
I don’t want to have an if statement in the function (not to slow it down) so my very ugly solution for this currently looks like:
switch_1 = True
if switch_1:
#defines my_function1() as my_function()
def my_function():
my_function_1()
else:
#defines my_function2() (that is just a little bit different from my_function1()) as my_function()
def my_function():
my_function_2()
def main():
#Some calculation steps before
array = my_function(args)
#Calculation steps after and calling the function
if __name__ == "__main__":
main()
This wouldn’t be an issue if just one such a switch was involved but let’s say that there are 10 switches that all alter my_function() just slightly and in different lines of the code. What I would like to do is to have the ability to somehow change the “intestines” of the function just regarding the switchches, from outside. In other words avoid the need to copy-paste most of the function (exception being the few altered lines) and use stacked if-else statements to select the correct version, which is just inconvinient, ugly and a nightmare when something has to be altered in all of the function versions (due to debugging, optimisation etc.).
I thought for example about having a class that “makes” the right version of my_function() when passed switch1-10 into it as arguments but i don’t know how to do that in an elegant way.
Jan Loskot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.