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?
This is not generally possible. If the frame corresponds to module-level code, then you can do
in Python 2, or
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:No code outside the text of a function can create variables local to that function.