Execute dynamically created function in another scope

45 Views Asked by At

I have got dynamically created funcion which accesses variable from another scope. For example:

def dynamically_generated_function():
    print(x)  # x is not defined in scope visible to this function

I would like to execute that funcion, but variable x comes from diffrent place. I have got access to scope of that place via proper frame from inspect.stack()

I see 2 solutions to achieve that:

  1. How to inject f_locals and f_globals from that frame to current frame?
  2. How to execute dynamically_generated_function within frame that has variable x defined?
0

There are 0 best solutions below