Skip to content

Commit 626f334

Browse files
Pijukatelclaude
andauthored
fix: make extra_name of try_import optional and the install hint reusable (#2247)
`extra_name` landed in #2208 as a required keyword-only argument in a patch release, breaking every external caller: `import apify.scrapy` fails with > TypeError: try_import() missing 1 required keyword-only argument: 'extra_name' This gives it a default — every call site here passes it explicitly, so user-facing messages are unchanged — and adds `package_name`, since the hint hardcoded `crawlee[<extra>]` and pointed SDK users at an extra that does not exist here. Also fixes two `IndexError` already in the helper: `e.args[0]` on an argless `ImportError` (the nested-guard case the docstring anticipates), and `extra_name[0]` on an empty list. Co-authored-by: Claude <noreply@anthropic.com>
1 parent e5faa4e commit 626f334

2 files changed

Lines changed: 52 additions & 11 deletions

File tree

‎src/crawlee/_utils/try_import.py‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,29 +12,44 @@
1212

1313

1414
@contextmanager
15-
def try_import(module_name: str, *symbol_names: str, extra_name: str | list[str]) -> Iterator[None]:
15+
def try_import(
16+
module_name: str,
17+
*symbol_names: str,
18+
extra_name: str | list[str] | None = None,
19+
package_name: str = 'crawlee',
20+
) -> Iterator[None]:
1621
"""Context manager to attempt importing symbols into a module.
1722
1823
If an `ImportError` is raised during the import, the symbols are replaced with `FailedImport` objects. When the
19-
error is a `ModuleNotFoundError`, the message also names the optional extra (or one of several) that installs the
20-
missing dependency. Other import errors, including those raised by a nested guard, keep their message as is.
24+
error is a `ModuleNotFoundError` and `extra_name` is given, the message also names the optional extra (or one of
25+
several) that installs the missing dependency. Other import errors, including those raised by a nested guard,
26+
keep their message as is.
27+
28+
Args:
29+
module_name: The name of the module the symbols are imported into.
30+
symbol_names: The names of the symbols being imported.
31+
extra_name: The optional extra (or extras) providing the dependency. When omitted, the error message is
32+
left as it is.
33+
package_name: The distribution whose extras are named in the message. Defaults to this package, and exists
34+
so that downstream packages reusing this helper can point users at their own extras.
2135
"""
2236
try:
2337
yield
2438
except ImportError as e:
25-
message = e.args[0]
26-
if isinstance(e, ModuleNotFoundError):
27-
message = f'{message}. {_get_install_hint(extra_name)}'
39+
message = str(e)
40+
if isinstance(e, ModuleNotFoundError) and extra_name:
41+
message = f'{message}. {_get_install_hint(extra_name, package_name)}'
2842
for symbol_name in symbol_names:
2943
setattr(sys.modules[module_name], symbol_name, FailedImport(message))
3044

3145

32-
def _get_install_hint(extra_name: str | list[str]) -> str:
46+
def _get_install_hint(extra_name: str | list[str], package_name: str) -> str:
3347
"""Build the sentence telling the user which extra installs the missing optional dependency."""
34-
if isinstance(extra_name, str):
35-
return f"Install the optional '{extra_name}' extra to use it: pip install 'crawlee[{extra_name}]'"
36-
extras = ', '.join(f"'{name}'" for name in extra_name)
37-
return f"Install one of the optional extras {extras} to use it, e.g. pip install 'crawlee[{extra_name[0]}]'"
48+
extras = [extra_name] if isinstance(extra_name, str) else list(extra_name)
49+
if len(extras) == 1:
50+
return f"Install the optional '{extras[0]}' extra to use it: pip install '{package_name}[{extras[0]}]'"
51+
names = ', '.join(f"'{name}'" for name in extras)
52+
return f"Install one of the optional extras {names} to use it, e.g. pip install '{package_name}[{extras[0]}]'"
3853

3954

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

‎tests/unit/_utils/test_try_import.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,29 @@ def test_nested_guard_keeps_the_inner_message(module_name: str, monkeypatch: pyt
5252

5353
assert sys.modules[module_name].OptionalSymbol.message == inner_message
5454
assert inner_message.count('pip install') == 1
55+
56+
57+
def test_omitted_extra_keeps_the_original_message(module_name: str) -> None:
58+
"""Without `extra_name` the message is left as it is, so external callers of the helper keep working."""
59+
with try_import(module_name, 'OptionalSymbol'):
60+
raise ModuleNotFoundError("No module named 'parsel'", name='parsel')
61+
62+
assert sys.modules[module_name].OptionalSymbol.message == "No module named 'parsel'"
63+
64+
65+
def test_install_hint_names_the_given_package(module_name: str) -> None:
66+
"""Downstream packages reusing the helper can point users at their own extras."""
67+
with try_import(module_name, 'OptionalSymbol', extra_name='scrapy', package_name='apify'):
68+
raise ModuleNotFoundError("No module named 'scrapy'", name='scrapy')
69+
70+
assert sys.modules[module_name].OptionalSymbol.message == (
71+
"No module named 'scrapy'. Install the optional 'scrapy' extra to use it: pip install 'apify[scrapy]'"
72+
)
73+
74+
75+
def test_import_error_without_arguments_is_handled(module_name: str) -> None:
76+
"""An `ImportError` carrying no message does not break the guard itself."""
77+
with try_import(module_name, 'OptionalSymbol', extra_name='parsel'):
78+
raise ImportError
79+
80+
assert sys.modules[module_name].OptionalSymbol.message == ''

0 commit comments

Comments
 (0)