Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor(content_fetcher): defer ContentFetcher import via PEP 562 __getattr__ (#5023)

Sb75bab80fdc0
diff --git a/changelog.d/+lazy-content-fetcher-imports.refactor.md b/changelog.d/+lazy-content-fetcher-imports.refactor.md
new file mode 100644
index 0000000000..add12a0a31
--- /dev/null
+++ b/changelog.d/+lazy-content-fetcher-imports.refactor.md
@@ -0,0 +1 @@
+`content_fetcher.ContentFetcher` is now resolved lazily on first attribute access (PEP 562 module `__getattr__`) instead of being eagerly imported in the package `__init__`. `url_classifier` (and any other import that goes through the `content_fetcher` package) no longer drags in the fetcher's transitive deps (`requests`, `playwright`, `bs4`, `lxml`, etc.), so minimal test setups and the citation formatter can stop using the disk-load workaround introduced in #4880. Public API is unchanged.
diff --git a/src/local_deep_research/content_fetcher/__init__.py b/src/local_deep_research/content_fetcher/__init__.py
index 363c56d180..d0664a5131 100644
--- a/src/local_deep_research/content_fetcher/__init__.py
+++ b/src/local_deep_research/content_fetcher/__init__.py
@@ -14,7 +14,29 @@ Usage:
print(result["content"])
"""
-from .fetcher import ContentFetcher
from .url_classifier import URLClassifier, URLType
__all__ = ["ContentFetcher", "URLClassifier", "URLType"]
+
+
+def __getattr__(name):
+ """Lazily resolve ``ContentFetcher`` on first attribute access.
+
+ ``fetcher`` transitively pulls in the full web/DB stack
+ (requests, playwright, … via ``research_library.downloaders``).
+ Deferring the import lets
+ ``from ...content_fetcher.url_classifier import URLClassifier``
+ stay cheap and lets minimal test setups import the package
+ without that dependency tree. See issue #4992.
+ """
+ if name == "ContentFetcher":
+ from .fetcher import ContentFetcher as _ContentFetcher
+
+ globals()["ContentFetcher"] = _ContentFetcher
+ return _ContentFetcher
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+def __dir__():
+ """Expose lazily-resolved names to ``dir()`` and tab completion."""
+ return sorted(set(globals()) | {"ContentFetcher"})
diff --git a/tests/content_fetcher/test_lazy_content_fetcher.py b/tests/content_fetcher/test_lazy_content_fetcher.py
new file mode 100644
index 0000000000..abe10eb22e
--- /dev/null
+++ b/tests/content_fetcher/test_lazy_content_fetcher.py
@@ -0,0 +1,249 @@
+"""
+Tests for the lazy-loading contract of ``content_fetcher``.
+
+Issue #4992: importing ``url_classifier`` (directly or via the package)
+must not drag in the heavy transitive deps that ``ContentFetcher`` pulls
+through ``fetcher`` → ``research_library.downloaders`` (requests,
+playwright, bs4, lxml, …). The package must expose ``ContentFetcher``
+on demand while keeping ``url_classifier`` cheap.
+
+The "heavy deps" assertions run in a clean subprocess so they don't
+disturb ``sys.modules`` for the rest of the test suite — purging
+``sys.modules`` mid-test breaks @patch decorators in sibling test files
+that captured pre-purge class objects.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+
+_HEAVY_FRAGMENTS = (
+ "requests",
+ "playwright",
+ "sqlalchemy",
+ "bs4",
+ "beautifulsoup",
+ "lxml",
+ "justext",
+ "trafilatura",
+ "readability",
+ "newspaper",
+ "safe_requests",
+ "downloaders.playwright",
+)
+
+
+def _measure_heavy_imports(import_stmt: str) -> list[str]:
+ """Run ``import_stmt`` in a fresh interpreter and return the heavy
+ modules pulled into ``sys.modules`` as a side effect."""
+ project_root = Path(__file__).resolve().parents[3]
+ script = textwrap.dedent(
+ f"""
+ import sys
+ before = set(sys.modules)
+ {import_stmt}
+ after = set(sys.modules)
+ new = sorted(after - before)
+ heavy = [
+ m for m in new
+ if any(frag in m.lower() for frag in {list(_HEAVY_FRAGMENTS)!r})
+ ]
+ for m in heavy:
+ print(m)
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ cwd=str(project_root),
+ check=True,
+ )
+ return [line for line in result.stdout.splitlines() if line]
+
+
+class TestUrlClassifierIsCheapToImport:
+ """Importing ``url_classifier`` must not pull heavy deps transitively.
+
+ This is the core promise of #4992 — without it, the
+ ``citation_formatter`` workaround (PR #4880) cannot be removed and
+ minimal test setups are forced to load the full web/DB stack.
+ """
+
+ def test_submodule_import_pulls_no_heavy_deps(self):
+ heavy = _measure_heavy_imports(
+ "import local_deep_research.content_fetcher.url_classifier as uc"
+ )
+ assert heavy == [], (
+ "url_classifier must import cleanly without the fetcher's "
+ f"transitive deps; pulled: {heavy}"
+ )
+
+ def test_from_url_classifier_import_pulls_no_heavy_deps(self):
+ heavy = _measure_heavy_imports(
+ "from local_deep_research.content_fetcher.url_classifier "
+ "import URLClassifier, URLType"
+ )
+ assert heavy == [], (
+ "``from ...content_fetcher.url_classifier import ...`` must "
+ f"not pull heavy deps; pulled: {heavy}"
+ )
+
+ def test_url_classifier_classification_still_works(self):
+ # Sanity check that we didn't break the actual API while making
+ # the import cheap.
+ from local_deep_research.content_fetcher.url_classifier import (
+ URLClassifier,
+ URLType,
+ )
+
+ assert URLClassifier.classify("https://arxiv.org/abs/2301.12345") == (
+ URLType.ARXIV
+ )
+ assert (
+ URLClassifier.classify("https://example.com/page.html")
+ == URLType.HTML
+ )
+
+
+class TestContentFetcherIsLazy:
+ """``ContentFetcher`` is exposed lazily so the heavy deps are not
+ loaded until something actually needs the fetcher."""
+
+ def test_content_fetcher_not_in_module_dict_until_accessed(self):
+ # Importing the package must not eagerly populate the global
+ # namespace with ContentFetcher — that's the contract PEP 562
+ # gives us. Run in a subprocess so we get a fresh module state
+ # regardless of what other tests in the suite have touched.
+ script = textwrap.dedent(
+ """
+ import local_deep_research.content_fetcher as cf
+ assert "URLClassifier" in vars(cf)
+ assert "URLType" in vars(cf)
+ assert "ContentFetcher" not in vars(cf), (
+ "ContentFetcher should be resolved via __getattr__, not "
+ "be eagerly present in module globals"
+ )
+ print("OK")
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ cwd=str(Path(__file__).resolve().parents[3]),
+ check=False,
+ )
+ assert result.returncode == 0, (
+ f"subprocess failed: stdout={result.stdout!r} stderr={result.stderr!r}"
+ )
+ assert result.stdout.strip() == "OK"
+
+ def test_attribute_access_triggers_lazy_load_and_caches(self):
+ import local_deep_research.content_fetcher as cf
+
+ cls = cf.ContentFetcher
+ assert cls.__name__ == "ContentFetcher"
+ # After first access, the class is cached in the module dict so
+ # subsequent lookups are O(1) globals() hits rather than going
+ # through __getattr__ again.
+ assert cf.__dict__["ContentFetcher"] is cls
+ assert cf.ContentFetcher is cls
+
+ def test_from_package_import_resolves_via_getattr(self):
+ from local_deep_research.content_fetcher import ContentFetcher
+ from local_deep_research.content_fetcher.fetcher import (
+ ContentFetcher as RealContentFetcher,
+ )
+
+ assert ContentFetcher is RealContentFetcher
+
+ def test_unknown_attribute_raises_attributeerror(self):
+ import local_deep_research.content_fetcher as cf
+
+ with pytest.raises(AttributeError, match="NoSuchName"):
+ cf.NoSuchName # noqa: B018
+
+
+class TestPublicApiIsUnchanged:
+ """The refactor must not change the package's public surface."""
+
+ def test_dunder_all_contains_expected_names(self):
+ import local_deep_research.content_fetcher as cf
+
+ assert set(cf.__all__) == {
+ "ContentFetcher",
+ "URLClassifier",
+ "URLType",
+ }
+
+ def test_dir_includes_lazy_name(self):
+ import local_deep_research.content_fetcher as cf
+
+ # __dir__ must surface ContentFetcher even though it isn't in
+ # module globals until first access — otherwise tab completion
+ # and introspection tools lose it.
+ assert "ContentFetcher" in dir(cf)
+ assert "URLClassifier" in dir(cf)
+ assert "URLType" in dir(cf)
+
+
+class TestHeavyDepsOnlyLoadWithContentFetcher:
+ """The whole point of #4992: heavy deps are deferred until the
+ fetcher is actually used. This test guards against accidental
+ re-introduction of eager imports in the package __init__."""
+
+ def test_subprocess_url_classifier_does_not_load_fetcher(self):
+ """In a clean interpreter, importing url_classifier must not
+ transitively load the fetcher module."""
+ script = textwrap.dedent(
+ """
+ import sys
+ import local_deep_research.content_fetcher.url_classifier as uc
+ print("local_deep_research.content_fetcher.fetcher" in sys.modules)
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ cwd=str(Path(__file__).resolve().parents[3]),
+ check=True,
+ )
+ assert result.stdout.strip() == "False", (
+ f"expected 'False', got {result.stdout.strip()!r}"
+ )
+
+ def test_subprocess_content_fetcher_access_loads_fetcher(self):
+ """Conversely, accessing ContentFetcher must trigger the fetcher
+ module to load — otherwise the lazy mechanism isn't wired up."""
+ script = textwrap.dedent(
+ """
+ import sys
+ import local_deep_research.content_fetcher as cf
+ before = "local_deep_research.content_fetcher.fetcher" in sys.modules
+ cf.ContentFetcher
+ after = "local_deep_research.content_fetcher.fetcher" in sys.modules
+ print(f"{before} {after}")
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ cwd=str(Path(__file__).resolve().parents[3]),
+ check=True,
+ )
+ before, after = result.stdout.strip().split()
+ assert before == "False", (
+ f"fetcher should NOT be loaded until access; before={before!r}"
+ )
+ assert after == "True", (
+ f"fetcher should be loaded after first access; after={after!r}"
+ )