Fetch variables from all functions in stack in Python

  Kiến thức lập trình

I want to build a utility that’s able to extract local variables from each frame in the call stack. Ideally I’d like to do this with a context manager. I want to capture certain variables for telemetry. Ideally it should look something like this.

with captures_variables():
  some_function_that_calls_other_stuff()

I want to capture the locals from the function and all other functions it calls going down the stack.

I’m unable to get the variables because once the function exists (e.g. after I yield in the context manager), the frames are no longer in the stack. If I capture the variables before (i.e. before yielding) then the frames aren’t yet available.

It appears I’d have to do the capturing while one of the functions is running. I don’t have control over the running function. I’m not sure how I should get it done.

LEAVE A COMMENT