Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created November 20, 2023 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/9d360de23084c30a6a92cc26da5ff0b5 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/9d360de23084c30a6a92cc26da5ff0b5 to your computer and use it in GitHub Desktop.
Context manager for temporarily overriding Python forking behavior.
from contextlib import contextmanager
from multiprocessing import get_start_method, set_start_method
from typing import Literal
@contextmanager
def ForkingBehavior(
*,
start_method: Literal['spawn', 'fork', 'forkserver'],
force: bool,
):
prev_start_method = get_start_method()
set_start_method(start_method, force=force)
try:
yield
finally:
set_start_method(prev_start_method, force=True)
if __name__ == "__main__":
print(f"before: {get_start_method()=}")
try:
with ForkingBehavior(start_method='forkserver', force=True):
print(f"inside: {get_start_method()=}")
raise ValueError
finally:
print(f"after: {get_start_method()=}")
#
# Produces:
#
# before: get_start_method()='spawn'
# inside: get_start_method()='forkserver'
# after: get_start_method()='spawn'
# Traceback (most recent call last):
# File "temporary_fork_behavior_setter.py.py", line 26, in <module>
# raise ValueError
# ValueError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment