lucas755
lucas755

Reputation: 45

Can I conditionally change which function I'm calling?

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?

Upvotes: 3

Views: 131

Answers (3)

Netwave
Netwave

Reputation: 42688

You can call them within the locals or globals dict:

locals()[funcName](p1, p2, p3)

Example:

>>> a = lambda x: x+1
>>> locals()['a'](2)
3

As commented below you may check if they are within expected:

if funcName in ["func1", "func2", "func3"]:
    locals()[funcName](p1, p2, p3)

Upvotes: 1

Swiffy
Swiffy

Reputation: 4693

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.

Upvotes: 1

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

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

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

funcs[funcName](p1, p2, p3)

Upvotes: 7

Related Questions