Python Forum
Call a Function contained in a Tuple - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Call a Function contained in a Tuple (/thread-19125.html)



Call a Function contained in a Tuple - SamGer - Jun-14-2019

Hallo Users,

I have a Tuple of Variables and corresponding to that a Tuple of functions. Now based on what variable is used a function needs to be called. Seeking help on calling the function from Tuple of function

Var_Tuple=('Var1','Var2','Var3')
Func_Tuple=('Func1()','Func2()','Func3()')

So if the user Types Var3 then the Func3() must be called.

Best Regards


RE: Call a Function contained in a Tuple - buran - Jun-14-2019

def spam():
    print('spam')
    
def eggs():
    print('eggs')
    
funcs = {'foo':spam, 'bar':eggs}

user_choice=input('foo or bar?')
funcs[user_choice]()
Output:
foo or bar?bar eggs >>>



RE: Call a Function contained in a Tuple - noisefloor - Jun-14-2019

Hi,

 Func_Tuple=('Func1()','Func2()','Func3()')
is _not_ a tuple containing functions, but a tuple containing strings.
Except this, having a varible name suffix stating the data structure tye doesn't make to much sense, as the data type is clearly visible from the code. Having this suffix is not really good style, so try to get rid of it as soon as you can.

As @buran showed, use a data structure with a mapping, with is a Python dict. That's the better way.

Regards, noisefloor


RE: Call a Function contained in a Tuple - SamGer - Jun-14-2019

Thank you for your valuable suggestions


RE: Call a Function contained in a Tuple - snippsat - Jun-14-2019

Can also show a way that i like better.
funcs[user_choice]() as @buran show have done many times,but have tired to go away for using it.
I think looking at () after a list can in some case be confusing,can also be using get() to do error checking.
Then it look like this.
def spam():
    return('spam')

def eggs():
    return('eggs')

def switch_case(user_choice):
    return {
        'foo': spam(),
        'bar': eggs(),
    }.get(user_choice, f'<{user_choice}> Not in Record')

user_choice = input("foo or bar? ")
print(switch_case(user_choice))
Output:
foo or bar? foo spam foo or bar? bar eggs foo or bar? car <car> Not in Record



RE: Call a Function contained in a Tuple - ThomasL - Jun-14-2019

@snippsat return is not a function so no need to use brackets
return 'spam' works fine. :-)


RE: Call a Function contained in a Tuple - snippsat - Jun-14-2019

(Jun-14-2019, 04:18 PM)ThomasL Wrote: @snippsat return is not a function so no need to use brackets
return 'spam' works fine. :-)
Thanks,did a rewrite of first example which had print('spam') then i just changed print with return,and did forget to remove ().


RE: Call a Function contained in a Tuple - ThomasL - Jun-14-2019

We are all humans ;-)