From 171dd012f9faeeabe4038225ce0b2d9421eec0ad Mon Sep 17 00:00:00 2001 From: Nate Hardison Date: Mon, 3 Mar 2025 16:46:12 -0800 Subject: [PATCH] Do a lazy import of the _main CLI module Importing the CLI code doubles the import time for httpx altogether. By importing lazily at runtime, the additional time only happens when running the httpx CLI, and not on every "import httpx". --- httpx/__init__.py | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/httpx/__init__.py b/httpx/__init__.py index e9addde071..b2715b5157 100644 --- a/httpx/__init__.py +++ b/httpx/__init__.py @@ -11,19 +11,29 @@ from ._types import * from ._urls import * -try: - from ._main import main -except ImportError: # pragma: no cover - def main() -> None: # type: ignore - import sys +# import the _main module lazily so that we only incur the extra import time +# for the CLI dependencies (click, rich, etc.) when intending to run the CLI +# and not on every import of httpx +def __getattr__(name: str): # type: ignore[no-untyped-def] + if name == "main": + try: + from ._main import main + except ImportError: # pragma: no cover - print( - "The httpx command line client could not run because the required " - "dependencies were not installed.\nMake sure you've installed " - "everything with: pip install 'httpx[cli]'" - ) - sys.exit(1) + def main() -> None: # type: ignore + import sys + + print( + "The httpx command line client could not run because the required " + "dependencies were not installed.\nMake sure you've installed " + "everything with: pip install 'httpx[cli]'" + ) + sys.exit(1) + + return main + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") __all__ = [ @@ -59,7 +69,6 @@ def main() -> None: # type: ignore "InvalidURL", "Limits", "LocalProtocolError", - "main", "MockTransport", "NetRCAuth", "NetworkError",