Repository navigation
new thread doesn't copy context of the parent thread #86981
Description
Activity
New thread doesn't copy context of the parent thread.
The minimal example to reproduce the issue:
from threading import Thread from contextvars import ContextVar foo: ContextVar[str] = ContextVar("foo") def temp(): print(foo.get()) foo.set("bar") t = Thread(target=temp) t.start() t.join()Is it expected behavior?
PEP-567 I didn't find anything regarding this case.
- added3.10 (EOL)end of lifeend of lifestdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Jan 3, 2021 Trust me, it's too late to fix this in 3.10.
As I read PEP-567, it looks like contextvars were not intended to be automatically copied into new threads. One of the examples describes how to use a copy of the current thread's context vars in another thread: https://peps.python.org/pep-0567/#offloading-execution-to-other-threads
Furthermore,
threading.local()doesn't automatically copy its values into new threads, and (as I understand)contextvarsis intended to be consistent withthreading.local().It is a bit surprising that scheduling an
asynciotask will copy the current context, while new threads get an empty context. But I expect the intention there was to be consistent withthreading.local(). (When you schedule an asyncio task, it's still going to be in the same thread and have access to the same thread-local variables.)tl;dr I think this is working as intended, and we can close this issue. (But I agree that the behavior is bit surprising.)
Thanks for doing this research; I agree that we can close this.
I don't want to speculate on the reasons for starting a new thread with an empty context; maybe it was an oversight, maybe it was being strict in the layering of dependencies (contexts depend on threads, so threads shouldn't depend on contexts), maybe it was something else. Maybe Yury could tell us, but he's got bigger things on his mind.
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsDone
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: