1

I have many functions with the same prefix. I want to use a combination of strings to invoke the function.

def func_plus_one(v):
    return v+1

def func_plus_two(v):
    return v+2

a='plus_one'
b='plus_two'

So how can I use 'func_'+a and 'func_'+b to use the function?

lanselibai
  • 1,203
  • 2
  • 19
  • 35

1 Answers1

3

If the functions are in the same module as the code needing to reference them, use the globals() of the module. You could call the function indicated by a using:

globals()['func_' + a](x)

If they are in another module, use getattr

getattr(some_module, func_' + a)(x)
donkopotamus
  • 22,114
  • 2
  • 48
  • 60