Skip to content

gh-109070: multiprocessing.get_context will not set the start method globally #135678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions Lib/multiprocessing/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,7 @@ def __init__(self, context):

def get_context(self, method=None):
if method is None:
if self._actual_context is None:
self._actual_context = self._default_context
return self._actual_context
return self._actual_context or self._default_context
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish I could say "or perhaps even just return self._default_context?" given the documentation for .get_context() today. BUT code relies on .get_context() to establish the actual set context and thus prevent it from being changed without force=True so that different contexts are not used between API surfaces at the default module level (Lib/multiprocessing/__init__.py sets module level attributes to be the multiprocessing.context._default_context instance attributes)

So I think we really are best off just documenting the existing behavior. As is already done for get_start_method() in the docs right below get_context() - https://docs.python.org/3/library/multiprocessing.html
Examples: All of the things defined in BaseContext that when used have a ctx=self.get_context() call in them. Once something is used with the default context we don't want to allow a set_start_method call to change it.

else:
return super().get_context(method)

Expand Down
6 changes: 6 additions & 0 deletions Lib/test/_test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5811,6 +5811,12 @@ def check_context(self, ctx):
p.join()
self.assertEqual(child_method, ctx.get_start_method())

def test_default_context(self):
# Get_context should not have side effect, see gh-109070.
multiprocessing.set_start_method(None, force=True)
multiprocessing.get_context()
self.assertIsNone(multiprocessing.context._default_context._actual_context)

def test_context(self):
for method in ('fork', 'spawn', 'forkserver'):
try:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:func:`multiprocessing.get_context` will not set the start method globally.
Loading