Guard script wrapper entrypoint import with if __name__ == "__main__"
#242
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 importvenv/bin/pip
and consequently runfrom pip._internal.cli.main import main
which is quite a heavy import.(And yup, this means that multiprocessing is often slower when running
tool
compared topython -m tool
if the application's__main__.py
uses aif __name__ == "__main__"
guard like pip.)I hope this use-case is convincing enough. I do not wish to drag the discussion out like with what happened with #239. If you'd like a demo that shows the performance implications, I'm happy to write one.
Concretely, this would let me remove this awful hack from my PR parallelizing .pyc compilation.
Finally, I'll note that distlib's original script template had the entrypoint import under
if __name__ == "__main__"
before pip's template was synced over to distlib ~6 years ago: ec0bcea. That seems to suggest that there shouldn't be any backwards compatibility concerns.