简体   繁体   中英

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.

eg

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM