Skip to content

Commit fab0285

Browse files
committed
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".
1 parent ce7a6e9 commit fab0285

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

httpx/__init__.py

+21-12
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,29 @@
1111
from ._types import *
1212
from ._urls import *
1313

14-
try:
15-
from ._main import main
16-
except ImportError: # pragma: no cover
1714

18-
def main() -> None: # type: ignore
19-
import sys
15+
# import the _main module lazily so that we only incur the extra import time
16+
# for the CLI dependencies (click, rich, etc.) when intending to run the CLI
17+
# and not on every import of httpx
18+
def __getattr__(name: str): # type: ignore[no-untyped-def]
19+
if name == "main":
20+
try:
21+
from ._main import main
22+
except ImportError: # pragma: no cover
2023

21-
print(
22-
"The httpx command line client could not run because the required "
23-
"dependencies were not installed.\nMake sure you've installed "
24-
"everything with: pip install 'httpx[cli]'"
25-
)
26-
sys.exit(1)
24+
def main() -> None: # type: ignore
25+
import sys
26+
27+
print(
28+
"The httpx command line client could not run because the required "
29+
"dependencies were not installed.\nMake sure you've installed "
30+
"everything with: pip install 'httpx[cli]'"
31+
)
32+
sys.exit(1)
33+
34+
return main
35+
36+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
2737

2838

2939
__all__ = [
@@ -59,7 +69,6 @@ def main() -> None: # type: ignore
5969
"InvalidURL",
6070
"Limits",
6171
"LocalProtocolError",
62-
"main",
6372
"MockTransport",
6473
"NetRCAuth",
6574
"NetworkError",

0 commit comments

Comments
 (0)