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

前端 未结 5 1797
再見小時候
再見小時候 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 05:07

    Something like this can work:

    def outer():
        def inner(i):
            return i + 10
    
    
    for f in outer.func_code.co_consts:
        if getattr(f, 'co_name', None) == 'inner':
    
            inner = type(outer)(f, globals())
    
            # can also use `types` module for readability:
            # inner = types.FunctionType(f, globals())
    
            print inner(42) # 52
    

    The idea is to extract the code object from the inner function and create a new function based on it.

    Additional work is required when an inner function can contain free variables. You'll have to extract them as well and pass to the function constructor in the last argument (closure).

提交回复
热议问题