Add `PyUnstable_InterpreterFrame_GetLocal` to read a local var from an interp. frame
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Proposal:
Add an unstable C API to read a single local variable of an internal interpreter frame by its localsplus index:
PyObject *
PyUnstable_InterpreterFrame_GetLocal(struct _PyInterpreterFrame *frame,
Py_ssize_t index);
Returns a new strong reference, with cell and free variables unboxed to their contents. Free variables are resolved from the function closure, so it also works on a frame that has not started executing (before COPY_FREE_VARS). index outside [0, co_nlocalsplus) returns NULL with an IndexError set; an unset or hidden slot returns NULL with no exception set. The frame is not modified.
Motivation
TorchDynamo (PyTorch JIT compiler) relies on the eval frame API (PEP 523), and one of the things it needs to do when it intercepts a frame is to read the frame's local variables.
CPython has 3 public APIs for reading frame locals, but none of them are suitable to be used in Dynamo:
PyFrame_GetLocals(PyFrameObject*)PyFrame_GetVar(PyFrameObject*, PyObject*)PyEval_GetFrameLocals(void)
The first two take a PyFrameObject* as first argument and there's no public way to get one from a _PyInterpreterFrame*. The last one (PyEval_GetFrameLocals) reads the current frame, and the frame might not be ready when Dynamo gets it.
So today PyTorch implements its own version of *_GetLocals, which relies on an interface that is fragile and hard to maintain.
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
Linked PRs
- gh-156134
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先查看链接的 PR gh-156134 和 Discourse 讨论,然后将提议的 PyUnstable_InterpreterFrame_GetLocal 行为与 PyTorch 的 framelocals_mapping.cpp 实现进行比较。当不稳定 C API 按照规范处理 localsplus 索引、cell 和 free 变量、未设置的槽位以及执行前的帧,并且具有适当的测试时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- api, backend
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100