Python Forum

Full Version: Call a Function contained in a Tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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 >>>
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
Thank you for your valuable suggestions
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
@snippsat return is not a function so no need to use brackets
return 'spam' works fine. :-)
(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 ().
We are all humans ;-)