How to move up and down between stack frames?

1.6k views Asked by At

Let's say, I obtain a stack frame using sys._getframe(1), which is obviously not the current frame.

Now I want to, in some way, move to the outer stack frame and execute a statement, like maybe x=10, so as to create a variable in that frame.

I understand its not a good practice to set a variable that way, but it just might be some other statement. So, the important part is how to move to that frame. with(frame) doesn't seem to work.

I think it should be possible, else why would there be two functions named getinnerframes and getouterframes in inspect module? Unless you can move to the outer frame, why would you even have inner frames?

Edit: In pdb module, they have two commands up and down with the docs saying

d(own) Move the current frame one level down in the stack trace (to a newer frame).

u(p) Move the current frame one level up in the stack trace (to an older frame).

Is this going to help with my case? If yes, how to use it?

1

There are 1 answers

4
user2357112 On

This is not generally possible. If the frame corresponds to module-level code, then you can do

exec 'x=10' in frame.f_globals, frame.f_locals

in Python 2, or

exec('x=10', frame.f_globals, frame.f_locals)

in Python 3. However, if the frame corresponds to a function call or class body, then this will execute x=10 as if it's embedded in a class statement nested within the frame's scope:

If two separate objects are given as globals and locals, the code will be executed as if it were embedded in a class definition.

No code outside the text of a function can create variables local to that function.