Accessing thread state from a module?

I am aware of the sys module and I can easily access the thread state I need using sys. However I would like to create a new module which does some of the things that are done in sys but specific to my needs.

So my question is: do modules (if they are written in C with python bindings) have any access to cpython state? Is there a way I can call something like:


From an external C module?


I think you’ll find what you’ll need here: Initialization, Finalization, and Threads — Python 3.9.2 documentation

Almost what I need.

I also need to access the parent frame. Looks like PyThreadState_GetFrame and PyThreadState_GetBack would be what I would use but these are not in the public api.

PyThreadState_GetFrame is defined in Include/pystate.h since Python 3.9, but it is excluded from the Limited API (PEP 384):

$ grep -r PyThreadState_GetFrame Include
 Include/pystate.h:PyAPI_FUNC(PyFrameObject*) PyThreadState_GetFrame(PyThreadState *tstate);