Repository navigation
Pass opaque state to PyContext_AddWatcher callback #127124
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Nov 22, 2024 - added a commit that references this issue
on Nov 22, 2024 void *argis a bit of a headache, and I'm not sure we have any precedent for it in the C API. There's a few things we need to worry about:- How do we deal with thread safety on the state?
- Who will manage the lifetime of it?
- What rules will that state have (e.g. can it hold Python objects? If it can, then how do we deal with reference counting and traversing it?)
These aren't unsolvable problems, but I think the approach would be much easier if we just allowed passing a Python object, which has answered all of these questions. If the user really wants some C data, they can use a capsule.
- addedinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)
on Nov 23, 2024 I can do
PyObject *instead ofvoid *. I suggestedvoid *because that's what I'm used to with pure C and thought it might be easier for developers connecting C code to Python. I was unaware of capsules; thanks for mentioning them.Spitballing: Instead of a function pointer + object, WDYT about taking a callable object? That would be more awkward to use from C, unless there's a utility function I'm unaware of that wraps a C function pointer inside a callable.
That might be better, it would unlock some more use cases. You can use
PyCFunction_Newto wrap a C function into a Python callable, but yeah it's slightly more painful to use.- added 6 commits that reference this issue
on Nov 24, 2024
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:
cpython/Include/cpython/context.h
Lines 39 to 55 in e8bb053
to:
The original idea was for the callback to get any required state from the current context, but:
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).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