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

前端 未结 5 1806
再見小時候
再見小時候 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:43

    A few years later, but the following snippet helped me:

    the_code = '''
    a = 1
    b = 2
    return_me = a + b
    '''
    
    loc = {}
    exec(the_code, globals(), loc)
    return_workaround = loc['return_me']
    print(return_workaround)  # 3
    

    exec() doesn't return anything itself, but you can pass a dict which has all the local variables stored in it after execution. By accessing it you have a something like a return.

    I hope it helps someone.

提交回复
热议问题