Skip to content
Advertisement

Way to call method depending on variable?

I already have a working, but in my oppinion not beautiful solution for a part of a long script.

My script uses several similar methods, that differ too much to combine. However I came to a point where I want to call one of those methods depending on a given variable.

The names of the methods are build up like this:

def read_A():
    #doing sth
def read_B():
    #doing sth else
def read_C():

etc.

Now I would like to call those methods in a pythonic way, when the letter ('A', 'B', 'C', …) is given as a variable.

A non-pythonic solution would be:

if var == "A":
    read_A()
if var == "B":
    read_B() .....

And I hope to find a more pythonic solution that allows me to call those methods simply like this:

var = "A"
read_var()      #This would call the method 'read_A()'

Please mind that the code above is only an image of what I hope to do, it is not a working example!

Advertisement

Answer

I dont see an issue with just using

if var == 'A':
    read_a()

but if you’d like to make it more ‘pythonic’ you could map your variables to the methods using a dictionary and execute it based on the result of what’s stored in your dictionary:

def read_a():
    print('Running method read_a')

def read_b():
    print('Running method read_b')

switch = {'A': read_a, 'B': read_b}

case = 'A'
switch.get(case)()
>> 'Running method read_a'
case = 'B'
switch.get(case)()
>> 'Running method read_b'
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement