Skip to content

Commit 6ffe214

Browse files
committed
Refactor preload error handling into _handle_import_error helper
Extract duplicated match on_error logic into a helper function. The warn_stacklevel parameter is required (no default) to ensure callers explicitly specify the correct level for warning messages. Thanks to Duane Griffin for the suggestion.
1 parent 54f9336 commit 6ffe214

File tree

1 file changed

+21
-24
lines changed

1 file changed

+21
-24
lines changed

Lib/multiprocessing/forkserver.py

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,21 @@ def ensure_running(self):
220220
#
221221
#
222222

223+
def _handle_import_error(on_error, modinfo, exc, *, warn_stacklevel):
224+
"""Handle an import error according to the on_error policy."""
225+
match on_error:
226+
case 'fail':
227+
raise
228+
case 'warn':
229+
warnings.warn(
230+
f"Failed to preload {modinfo}: {exc}",
231+
ImportWarning,
232+
stacklevel=warn_stacklevel + 1
233+
)
234+
case 'ignore':
235+
pass
236+
237+
223238
def _handle_preload(preload, main_path=None, sys_path=None, sys_argv=None,
224239
on_error='ignore'):
225240
"""Handle module preloading with configurable error handling.
@@ -247,37 +262,19 @@ def _handle_preload(preload, main_path=None, sys_path=None, sys_argv=None,
247262
# Catch broad Exception because import_main_path() uses
248263
# runpy.run_path() which executes the script and can raise
249264
# any exception, not just ImportError
250-
match on_error:
251-
case 'fail':
252-
raise
253-
case 'warn':
254-
import warnings
255-
warnings.warn(
256-
f"Failed to preload __main__ from {main_path!r}: {e}",
257-
ImportWarning,
258-
stacklevel=2
259-
)
260-
case 'ignore':
261-
pass
265+
_handle_import_error(
266+
on_error, f"__main__ from {main_path!r}", e, warn_stacklevel=2
267+
)
262268
finally:
263269
del process.current_process()._inheriting
264270

265271
for modname in preload:
266272
try:
267273
__import__(modname)
268274
except ImportError as e:
269-
match on_error:
270-
case 'fail':
271-
raise
272-
case 'warn':
273-
import warnings
274-
warnings.warn(
275-
f"Failed to preload module {modname!r}: {e}",
276-
ImportWarning,
277-
stacklevel=2
278-
)
279-
case 'ignore':
280-
pass
275+
_handle_import_error(
276+
on_error, f"module {modname!r}", e, warn_stacklevel=2
277+
)
281278

282279
# gh-135335: flush stdout/stderr in case any of the preloaded modules
283280
# wrote to them, otherwise children might inherit buffered data

0 commit comments

Comments
 (0)