I have a subclass of Thread that I use across my project. In this class, I pass in the ContextVar manually. However, at times (once or twice a day), I notice that the ContextVar in the child thread is not set (reverted to a default value).
class MyThread(Thread): def __init__( self, group: None = None, target: Callable[..., Any] | None = None, name: str | None = None, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, *, daemon: bool | None = None, ): super().__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon) self.my_resource = get_resource_info() def run(self): self._exception = None try: set_my_resource_info(self.my_resource.name, self.my_resource.kind) self._return_value = super().run() except BaseException as e: self._exception = e def join(self, timeout: float | None = None): super().join(timeout) if self._exception: raise self._exception return self._return_value And in another module I have:
@dataclass class MyResourceInfo: name: str kind: str ="unknown" resource_info: ContextVar[MyResourceInfo] = ContextVar( 'my_resource_info', default=MyResourceInfo(name=get_default_resource_name()), ) def set_resource_info(name: str, kind: str = 'unknown') -> Token[MyResourceInfo]: return resource_info.set(MyResourceInfo(name=name, kind=kind)) Why does the context var revert to default value intermittently in child threads?
.runitself, and retry the setting.Python 3.10.14running inpython:3.10-slim-bookwormdocker container.