How do I get the return value when using Python exec on the code object of a function?

前端 未结 5 1807
再見小時候
再見小時候 2020-12-06 04:04

For testing purposes I want to directly execute a function defined inside of another function.

I can get to the code object of the child function, through the code (

5条回答
  •  春和景丽
    2020-12-06 04:44

    Here's a way to return a value from exec'd code:

    def exec_and_return(expression):
        exec(f"""locals()['temp'] = {expression}""")
        return locals()['temp']
    

    I'd advise you to give an example of the problem you're trying to solve. Because I would only ever use this as a last resort.

提交回复
热议问题