[issue39660] Contextvars: Optional callbacks on state change

Leonard Lausen report at bugs.python.org
Thu Feb 20 18:40:40 EST 2020


Leonard Lausen <leonard at lausen.nl> added the comment:

> No, but there's C API that you can use to get/set contextvars. If a C library
> is hard coded to use threadlocals I'm afraid there's nothing we can do about
> it except fixing their C code to make state storage pluggable.

I agree the C library could check the Python state. On the other hand, the Python frontend may be just one of multiple supported language frontends of the library. So it seems preferable if Python could tell the library when to change state.

> What library do you have in mind?

MXNet has such a thread-local C API to enable / disable recording for autograd. https://github.com/apache/incubator-mxnet/blob/9b38df0622fec677e6b4891dfc4c10295359996d/include/mxnet/c_api.h#L1260-L1266

> Theoretically yes, for debug purposes at least. But I still fail to see how
> you could use that API even if it existed.

Consider we are in "context 1". When we change the state in the C library by calling `old_state = lib.set_state(new_state)`, we get to know the prior state. When switching to "context 2", `lib.set_state(old_state)` should be called. When switching back to "context 1", `lib.set_state(new_state)` should be called again. It's analogous to contextvars.

Would there be too much overhead if allowing specification of a python function that contextvars calls on context changes?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39660>
_______________________________________


More information about the Python-bugs-list mailing list