Python Is it possible to recreate a whole call stack?

774 Views Asked by At

I'm interested in experimenting with python. I know I can inspect and inject local and global variables into a frame using frame.f_locals and frame.f_globals, but I am now itching to create a full call stack.

What is keeping me from just changing the stack information is the fact that python doesn't allow me to change it.

I have actually considered programmatically transforming the python module I am using, in order to simulate winding the stack. But I am aware it is a terrible solution because client code usage of if, while, with and try would easily break my code.

I've also looked at manipulating frame.f_back, to no avail. It's read-only.

>>> import sys
... 
... frm = sys._getframe()
... 
... frm.f_back = None
Traceback (most recent call last):
  File "<pyshell#4>", line 5, in <module>
    frm.f_back = None
TypeError: readonly attribute

What I'm trying to do

As an experiment, I'm trying to implement fork() across a network.

I'm aware stackless python may have what I want, but it's still impossible to change the frame.f_back attribute.

3

There are 3 best solutions below

0
Pavel Anossov On
>>> type(sys._getframe())()

TypeError: cannot create 'frame' instances

Sorry.

1
Ankur Ankan On

Have a look on Online Python Tutor (http://www.pythontutor.com/). What it does is that it captures frames during execution to create visualization of python code. So, you could use the captured frames.

0
Oin On

You should look at the AST module and the symtable module