From ad184c3d708762cffe4813d1cdac6a3cd640eb99 Mon Sep 17 00:00:00 2001 From: Richard Si Date: Sun, 13 Apr 2025 19:50:07 -0400 Subject: [PATCH] Guard script wrapper entrypoint import with if __main__ This way, the entrypoint will only be imported if the script wrapper is ran directly. This is beneficial for applications that use multiprocessing. multiprocessing imports the `__main__` module while initializing new workers to restore any global state the parallelized logic may rely on (e.g., a package-wide logger). Unfortunately, if the application is called using the console script wrapper (e.g., `pip install`), then the wrapper is the main module. For pip, this means every child process will import `venv/bin/pip` and consequently run `from pip._internal.cli.main import main` which is quite a heavy import. (And yup, this means that multiprocessing is often slower when running`pip` compared to `python -m pip` if the application's `__main__.py` uses a `if __main__` guard like pip.) --- distlib/scripts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distlib/scripts.py b/distlib/scripts.py index b1fc705..195dc3f 100644 --- a/distlib/scripts.py +++ b/distlib/scripts.py @@ -42,8 +42,8 @@ SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*- import re import sys -from %(module)s import %(import_name)s if __name__ == '__main__': + from %(module)s import %(import_name)s sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(%(func)s()) '''