Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I conditionally change which function I'm calling?

Tags:

python

Sorry if this has been asked before, but I couldn't find the words to search that would give me the answer I'm looking for.

I'm writing a script that contains a helper function, which, in turn, can call one of several functions which all take the same parameters. In this helper function, I end up having strings of this:

if funcName="func1":
  func1(p1, p2, p3)
elif funcName="func2":
  func2(p1, p2, p3)
elif funcName="func3":
  func3(p1, p2, p3)
...

I know that I could use another helper function that would also take the funcName string and distribute it to the appropriate function, but is there a better way to do it? What my brain wants to do is this:

funcName(p1, p2, p3)

That way I could call an arbitrary function name if I want to. Is something like that possible?

like image 299
lucas755 Avatar asked Nov 22 '25 06:11

lucas755


2 Answers

Yes, you can, by using a dict mapping names to functions:

funcs = dict(
    func1=func1,
    func2=func2,
    func3=func3
)

funcs[funcName](p1, p2, p3)
like image 157
GingerPlusPlus Avatar answered Nov 23 '25 20:11

GingerPlusPlus


If you put the functions inside an object like so:

var funcs = 
{
    f1: function() {},
    f2: function() {},
    f3: function() {}
}

You can do funcs['f1']() for example.

like image 35
Swiffy Avatar answered Nov 23 '25 18:11

Swiffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!