Skip to content

Commit 56bca2a

Browse files
authored
fix: Name the extra to install in optional-dependency import errors (#1046)
Accessing a symbol guarded by `try_import` without its extra installed raises an `ImportError` that now also names the extra to install: ``` No module named 'httpx2'. Install the optional 'httpx' extra to use it: pip install 'apify-client[httpx]' ``` `try_import` takes `extra_name` next to `dependency_name`, and both guarded sites (`httpx`, `brotli`) pass it. *✍️ Drafted by Claude Code*
1 parent 21c7b07 commit 56bca2a

5 files changed

Lines changed: 21 additions & 8 deletions

File tree

‎src/apify_client/_utils/try_import.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ class ImportState:
1919

2020

2121
@contextmanager
22-
def try_import(module_name: str, *symbol_names: str, dependency_name: str) -> Iterator[ImportState]:
22+
def try_import(module_name: str, *symbol_names: str, dependency_name: str, extra_name: str) -> Iterator[ImportState]:
2323
"""Context manager to attempt importing symbols into a module.
2424
25-
If the named optional dependency is missing, the symbols are replaced with `FailedImport` objects. Import errors
26-
caused by the importing module itself or by another dependency are propagated instead of being masked.
25+
If the named optional dependency is missing, the symbols are replaced with `FailedImport` objects whose message
26+
names the extra that installs it. Import errors caused by the importing module itself or by another dependency
27+
are propagated instead of being masked.
2728
"""
2829
state = ImportState()
2930
try:
@@ -32,8 +33,12 @@ def try_import(module_name: str, *symbol_names: str, dependency_name: str) -> It
3233
if exc.name != dependency_name:
3334
raise
3435
state.available = False
36+
message = (
37+
f"{exc.args[0]}. Install the optional '{extra_name}' extra to use it: "
38+
f"pip install 'apify-client[{extra_name}]'"
39+
)
3540
for symbol_name in symbol_names:
36-
setattr(sys.modules[module_name], symbol_name, FailedImport(exc.args[0]))
41+
setattr(sys.modules[module_name], symbol_name, FailedImport(message))
3742

3843

3944
def install_import_hook(module_name: str) -> None:

‎src/apify_client/http_clients/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
'HttpxHttpClient',
1414
'HttpxHttpClientAsync',
1515
dependency_name='httpx2',
16+
extra_name='httpx',
1617
) as _httpx_import:
1718
from apify_client.http_clients._httpx import HttpxHttpClient, HttpxHttpClientAsync
1819

‎src/apify_client/http_compressors/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
# `brotli` is an optional extra, so it's wrapped in try_import. Accessing `BrotliHttpCompressor`
1111
# without the extra installed raises a clear ImportError instead of failing at package import time.
12-
with _try_import(__name__, 'BrotliHttpCompressor', dependency_name='brotli') as _brotli_import:
12+
with _try_import(__name__, 'BrotliHttpCompressor', dependency_name='brotli', extra_name='brotli') as _brotli_import:
1313
from apify_client.http_compressors._brotli import BrotliHttpCompressor
1414

1515
if _brotli_import.available:

‎tests/unit/test_pluggable_http_client.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@ def find_spec(self, name, *_args):
395395
getattr(module, name)
396396
except ImportError as exc:
397397
assert "No module named 'httpx2'" in str(exc)
398+
assert "pip install 'apify-client[httpx]'" in str(exc)
398399
else:
399400
raise AssertionError(f'{name} did not raise ImportError')
400401
"""

‎tests/unit/test_utils.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_try_import_only_handles_the_named_missing_dependency() -> None:
4242
try:
4343
with (
4444
pytest.raises(ModuleNotFoundError, match='broken-transitive'),
45-
try_import(module_name, 'OptionalSymbol', dependency_name='optional-package'),
45+
try_import(module_name, 'OptionalSymbol', dependency_name='optional-package', extra_name='optional-extra'),
4646
):
4747
raise ModuleNotFoundError('broken-transitive', name='broken-transitive')
4848
assert not hasattr(sys.modules[module_name], 'OptionalSymbol')
@@ -51,14 +51,20 @@ def test_try_import_only_handles_the_named_missing_dependency() -> None:
5151

5252

5353
def test_try_import_records_the_named_missing_dependency() -> None:
54-
"""A genuinely missing optional dependency is converted to a failed-import placeholder."""
54+
"""A genuinely missing optional dependency becomes a failed-import placeholder that names the extra to install."""
5555
module_name = 'test_missing_optional_import_module'
5656
sys.modules[module_name] = ModuleType(module_name)
5757
try:
58-
with try_import(module_name, 'OptionalSymbol', dependency_name='optional-package') as state:
58+
with try_import(
59+
module_name, 'OptionalSymbol', dependency_name='optional-package', extra_name='optional-extra'
60+
) as state:
5961
raise ModuleNotFoundError("No module named 'optional-package'", name='optional-package')
6062
assert state.available is False
6163
assert isinstance(sys.modules[module_name].OptionalSymbol, FailedImport)
64+
assert sys.modules[module_name].OptionalSymbol.message == (
65+
"No module named 'optional-package'. Install the optional 'optional-extra' extra to use it: "
66+
"pip install 'apify-client[optional-extra]'"
67+
)
6268
finally:
6369
del sys.modules[module_name]
6470

0 commit comments

Comments
 (0)