Michael Wiles
Michael Wiles

Reputation: 21194

How do you call a function defined in the current function by its name (a string)

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?

Upvotes: 0

Views: 122

Answers (2)

Mario Ishac
Mario Ishac

Reputation: 5907

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().

Upvotes: 4

Lev M.
Lev M.

Reputation: 6269

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.

Upvotes: 0

Related Questions