0

How to call a function when it's name is stored in a string, has already been answered.

What I want to know is how do I do this if the function I'm wanting to call is defined in my local scope.

This differs from the other questions as they are not referring to calling a function by name when the function is inside another function.

e.g

def outer():
   
    def inner():
        # code for inner

    method_to_call = 'inner'
   
    # call inner by the value of method_to_call

So in the above code how do I call the function defined by the value in method_to_call?

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101
  • Does this help? https://stackoverflow.com/questions/2283210/python-function-pointer – thekid77777 Jul 17 '20 at 22:55
  • Are you *getting* the name in a string, or do you just think you need its name in a string? You can store a reference to the function in another variable: `method_to_call = inner`, then `method_to_call()`. – chepner Jul 17 '20 at 22:55
  • Does this answer your question? [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – jdaz Jul 17 '20 at 22:57
  • Does this answer your question? [A function inside a function Python](https://stackoverflow.com/questions/28400074/a-function-inside-a-function-python) – Akshat Zala Jul 22 '20 at 05:25

2 Answers2

4

You can use locals():

def outer():
    def inner():
        print("Called.")

    method_to_call = 'inner'

    locals()[method_to_call]()

After calling outer, "Called." is printed.

Note that there will be an error if there is a non-callable named inner (for example, having inner = "abc" will cause this).

However, as the comments say, this is only useful if you're getting the name inner from somewhere else (let's say input). If you already know what local function you want to call beforehand, it'd be better to use inner directly instead of through locals().

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
0

In Python you can use eval to convert any string to code and execute it.

def outer():
    def inner():
        # code for inner

    method_to_call = 'inner'

    eval(method_to_call + '()')

Note, that the string must contain valid Python code, so in this case you would need to add parenthesis () to the name of the function, to create a call statement, as you would write it in a normal call.

Lev M.
  • 6,088
  • 1
  • 10
  • 23