Pass opaque state to PyContext_AddWatcher callback
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Proposal:
I would like to change the Context watcher C API (new to v3.14, see #119333) to pass an opaque pointer to the callback. Specifically, change:
to:
/*
* Context object watcher callback function. arg is the same pointer passed to
* PyContext_AddWatcher when the callback was registered. The object passed to
* the callback is event-specific; see PyContextEvent for details.
*
* if the callback returns with an exception set, it must return -1. Otherwise
* it should return 0
*/
typedef int PyContext_WatchCallback(
void *arg, PyContextEvent event, PyObject *obj);
/*
* Register a per-interpreter callback that will be invoked for context events.
* arg is an optional opaque pointer that is passed back to the callback; it
* can be used to manage state if desired.
*
* Returns a handle that may be passed to PyContext_ClearWatcher on success,
* or -1 and sets and error if no more handles are available.
*/
PyAPI_FUNC(int) PyContext_AddWatcher(
PyContext_WatchCallback *callback, void *arg);
The original idea was for the callback to get any required state from the current context, but:
- The config/state is not guaranteed to be available in the context. For example, the Python code can do
ctx = contextvars.Context()instead ofctx = contextvars.copy_context(). Or it can docopy_context(), but early during initialization and squirrel the context away for later use. The latter seems plausible for 3rd party libraries (where the user might not have much control). - The same watcher callback cannot be registered multiple times simultaneously, each with its own config/state. This came up while I was refactoring
TestContextObjectWatchersto add some more tests for a change I’m working on.
I’m not sure how likely either is to come up in normal use, but I think it is worth changing the design before the 3.14 release cements it.
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
https://discuss.python.org/t/v3-14a1-design-limitations-of-pycontext-addwatcher/68177/4
cc @fried
Linked PRs
- gh-127140
- gh-127247
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Include/cpython/context.h 中的 Context watcher 声明开始,检查 Lib/test/test_capi/test_watchers.py,尤其是 TestContextObjectWatchers。在开始之前检查链接的 PR,然后验证已注册的 opaque pointer 能够传递到 callback,并且 watcher 测试覆盖更新后的 API 且通过。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- api
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 30/100