Created
November 20, 2023 22:12
-
-
Save malcolmgreaves/9d360de23084c30a6a92cc26da5ff0b5 to your computer and use it in GitHub Desktop.
Context manager for temporarily overriding Python forking behavior.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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