I have a file three_ways.py. There I have 3 functions for calculating 3 different y.
# The content of error_metrics.py
def way_1(x1, x2):
y = x1 - x2
return y
def way_2(x1, x2)
y = x1 ** 2 - x2 ** 2
return y
def way_3(x1, x2)
y = x1 * x2
return y
In my main (another) py-file, I want to design a function get_y(). It accepts a string argument to control which way to use.
way = 'way_2'
y = get_y(x1, x2, way)
I could use if-elif statement, see below. But I want avoid using if-elif. Because there can be arbitrary number of functions of different way_n(), n can be any number. Whenever I add a way_x() function in the file three_ways.py, I will have to make another elif statement in the function get_y(). And when n gets larger, the whole codes will be hard to read.
# starting point for making the function of get_y()
import three_ways
def get_y(x1, x2, way):
if way == 'way_1':
y = three_ways.way_1(x1, x2)
elif way == 'way_2':
y = three_ways.way_2(x1, x2)
elif way == 'way_3':
y = three_ways.way_3(x1, x2)
else:
print('Not implemented yet')
return y
So could you please help me with building such a function? It should be efficient, elegant, pythonic, and no if-elif statement. I am using Python3.
Thanks in advance.
way_x()to call. So I cannot pass the function as an argument. Because I am designing an user interface. The user will type the function name, and the program will read the typed name as string, and call the corresponding function.