aura
aura

Reputation: 543

How to read string and call function from a separate file, python 3

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.

Upvotes: 0

Views: 55

Answers (1)

Felk
Felk

Reputation: 8224

If you really want to do exactly what you described, you can look the function up using getattr:

way_func = getattr(three_ways, way)
y = way_func(x1, x2)

But because Python supports first-class-functions (functions can be passed around just like other data types), it's preferable to do what Rob said, which is just passing the function itself:

def get_y(x1, x2, way_func):
    return way_func(x1, x2)
get_y(4, 2, three_ways.way_2)

Upvotes: 1

Related Questions