3

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?

lucas755
  • 45
  • 1
  • 4

3 Answers3

7

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

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

funcs[funcName](p1, p2, p3)
GingerPlusPlus
  • 4,634
  • 1
  • 24
  • 47
1

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.

Piwwoli
  • 1,570
  • 1
  • 13
  • 32
1

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)
Netwave
  • 23,907
  • 4
  • 31
  • 58