I agree with @jsbueno that the contextvar API is painful to use.
I also create some higher level wrapper to simplify the usage: https://etils.readthedocs.io/en/latest/edc.html#wrap-fields-around-contextvar
from etils import edc
@edc.dataclass
@dataclasses.dataclass
class Scope:
is_active: edc.ContextVar[bool] = False
@contextlib.contextmanager
def activate(self):
self.is_active = True
try:
yield
finally:
self.is_active = False
scope = Scope()
# Each thread/coroutine will have their own version
with scope.activate():
...