httpx icon indicating copy to clipboard operation
httpx copied to clipboard

Do CLI import in __main__, not __init__

Open natehardison opened this issue 7 months ago • 0 comments
trafficstars

Summary

From https://github.com/encode/httpx/discussions/3523

Importing the _main.py module in httpx/__init__.py adds 0.087s worth of import time on my machine (MacBook M1 Pro, 32 GB RAM, macOS 15.3.1) running Python 3.13.2.

It's certainly not a huge amount of time in the absolute, but it roughly doubles the amount of time it takes to import httpx, even when you're not intending to run the CLI. Here's an import time graph generated using tuna on the output of python -X importtime -c "import httpx" > import.log

Screenshot 2025-03-03 at 4 15 23 PM

This PR adds httpx/__main__.py that does the import instead. This also allows python -m httpx as in https://github.com/encode/httpx/discussions/3216.

It does change the public API: httpx.main becomes the (more ungainly) httpx.__main__.main.

Checklist

  • [x] I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • [x] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • [x] I've updated the documentation accordingly.

natehardison avatar Apr 08 '25 23:04 natehardison