From b84edac0638ee0c20a41c1e72a81babb6760c149 Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 4 Dec 2026 14:26:55 +0300 Subject: [PATCH] fix: discover functions that shadow their submodules --- great_docs/_apiref/introspect.py | 49 ++++++++++++++--- great_docs/_reference/discovery.py | 52 +++++++++++++++--- great_docs/_reference/exports.py | 19 ++++++- great_docs/_reference/probe.py | 32 ++++++++--- tests/test_reference_exports.py | 12 ++-- tests/test_submodule_references.py | 88 ++++++++++++++++++++++++++++++ 6 files changed, 219 insertions(+), 33 deletions(-) diff --git a/great_docs/_apiref/introspect.py b/great_docs/_apiref/introspect.py index 4f0e5b85..f7dcb2d3 100644 --- a/great_docs/_apiref/introspect.py +++ b/great_docs/_apiref/introspect.py @@ -264,6 +264,30 @@ def _split_path(path: str) -> tuple[str, str | None]: return module_path, object_path or None +def shadowing_reexport(module: gf.Module) -> gf.Alias | None: + """ + Recover a function re-exported under its own submodule's name + + The static model keeps the submodule at that path. The parent still records + the import of the function, which can be documented as a separate binding. + """ + parent = module.parent + if not isinstance(parent, gf.Module): + return None + imported = parent.imports.get(module.name, "") + if not imported.startswith(f"{module.path}."): + return None + name = imported.removeprefix(f"{module.path}.") + member = module.members.get(name) + if member is not None: + try: + if member.kind is gf.Kind.FUNCTION: + return gf.Alias(module.name, member, parent=parent) + except (gf.AliasResolutionError, gf.CyclicAliasError, KeyError): + return None + return None + + def _static_object( module_path: str, object_path: str | None, @@ -290,7 +314,7 @@ def _static_object( : The node at the path. An imported name comes back as an alias, and a function or attribute reached through an aliased parent keeps that - parent. + parent. An object path can name a function that shadows its submodule. Raises ------ @@ -301,6 +325,10 @@ def _static_object( # griffe uses only periods for the path griffe_path = f"{module_path}.{object_path}" if object_path else module_path obj = loader.modules_collection[griffe_path] + if object_path is not None and isinstance(obj, gf.Module): + alias = shadowing_reexport(obj) + if alias is not None: + return alias parent = loader.modules_collection[griffe_path.rsplit(".", 1)[0]] if isinstance(parent, gf.Alias) and isinstance(obj, (gf.Function, gf.Attribute)): @@ -778,14 +806,21 @@ def _locate_runtime_attr( raise else: continue - if isinstance(value, ModuleType) and loader is not None: - modelled_module, remaining = _split_path( - _dynamic_path(path.replace(":", "."), loader) - ) - if modelled_module not in (module_path, value.__name__): + if loader is not None and (isinstance(value, ModuleType) or callable(value)): + replacement_path = _dynamic_path(path.replace(":", "."), loader) + modelled_module, remaining = _split_path(replacement_path) + if isinstance(value, ModuleType): + retry = modelled_module not in (module_path, value.__name__) + else: + # Only retry below the module whose binding the callable displaced. + binding_path = f"{module_path}.{'.'.join(names[:index])}" + retry = modelled_module == binding_path or modelled_module.startswith( + f"{binding_path}." + ) + if retry: replacement = import_project_module(modelled_module) return _locate_runtime_attr( - replacement, modelled_module, remaining, path, loader + replacement, modelled_module, remaining, replacement_path, loader ) return _locate_declaration(canonical_path or path, name, path, loader) diff --git a/great_docs/_reference/discovery.py b/great_docs/_reference/discovery.py index 6f978790..a01d2f41 100644 --- a/great_docs/_reference/discovery.py +++ b/great_docs/_reference/discovery.py @@ -1,9 +1,8 @@ """ Export discovery and categorisation for the generated API reference -Every function reads a package that griffe has already loaded, so none of them imports the -package. A caller that needs to know whether the renderer can document a path passes that check -in. +Read a package that Griffe has already loaded. A caller can check whether the renderer can +document a path and resolve functions that the package exports under a submodule's name. """ from __future__ import annotations @@ -16,7 +15,7 @@ from .._apiref._exports import declared_exports from .._apiref._type_checks import ClassKind, attribute_kind, class_kind, function_kind -from .._apiref.introspect import get_object +from .._apiref.introspect import get_object, shadowing_reexport from .._build.steps import BuildError if TYPE_CHECKING: @@ -332,7 +331,11 @@ def _drop_excluded(names: list[str], config: Config, *, report: Callable[[str], def discover_exports( - package: gf.Module, config: Config, *, report: Callable[[str], None] + package: gf.Module, + config: Config, + *, + report: Callable[[str], None], + runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None, ) -> list[str] | None: """ Find the names a package exports that the reference can document @@ -356,6 +359,8 @@ def discover_exports( The configuration whose `exclude`, `auto_include` and `no_auto_exclude` settings apply. report A callback that receives a line for each group of dropped names. + runtime_function + Recover a function at a name that static analysis assigns to a submodule. Returns ------- @@ -376,8 +381,8 @@ def discover_exports( if package.exports is None and "__all__" not in members: submodules: dict[str, bool] = {} for name in candidates: - member = members[name] try: + member = _export_binding(members[name], runtime_function) if member.kind is gf.Kind.MODULE: submodules[name] = member.exports is not None or "__all__" in member.members except (gf.CyclicAliasError, gf.AliasResolutionError, KeyError): @@ -448,6 +453,7 @@ def categorise_exports( *, renderable: Callable[[str], bool], report: Callable[[str], None], + runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None, ) -> Categories: """ Sort a package's exports into the groups of the API reference @@ -474,6 +480,8 @@ def categorise_exports( `package:Class.method`. report A callback that receives a line for each class and for each name left out. + runtime_function + Recover a function at a name that static analysis assigns to a submodule. Returns ------- @@ -494,8 +502,9 @@ def categorise_exports( unresolved.append(name) continue try: + obj = _export_binding(package.members[name], runtime_function) _categorise_export( - package, name, exported, categories, renderable=renderable, report=report + package, name, obj, exported, categories, renderable=renderable, report=report ) except gf.CyclicAliasError: report(f" Warning: Cyclic alias detected for '{name}', excluding from docs") @@ -512,9 +521,29 @@ def categorise_exports( return categories +def _export_binding( + member: gf.Object | gf.Alias, + runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None, +) -> gf.Object | gf.Alias: + """ + Use the function binding when the static model gives its name to a submodule + """ + if member.kind is not gf.Kind.MODULE: + return member + if isinstance(member, gf.Module) and (alias := shadowing_reexport(member)) is not None: + return alias + if runtime_function is not None: + module = member.final_target if isinstance(member, gf.Alias) else member + candidate = module.members.get(module.name) + if candidate is not None and candidate.kind is gf.Kind.FUNCTION: + return runtime_function(member.name) or member + return member + + def _categorise_export( package: gf.Module, name: str, + obj: gf.Object | gf.Alias, exported: set[str], categories: Categories, *, @@ -530,6 +559,8 @@ def _categorise_export( The loaded package. name The export, which the package defines. + obj + The object exposed under the export name. exported All the package's exports, whose names an exported module does not repeat. categories @@ -539,7 +570,6 @@ def _categorise_export( report A callback that receives the line describing a class. """ - obj = package.members[name] kind = obj.kind if kind is gf.Kind.CLASS: categories[_class_group(obj)].append(name) @@ -850,6 +880,8 @@ def _found_statically(path: str) -> bool: def categorise_references( package: gf.Module, reference: Iterable[object], + *, + runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None, ) -> Categories: """ Sort the names a `reference:` setting lists into the groups of the API reference @@ -866,6 +898,8 @@ def categorise_references( The loaded package. reference The sections of the `reference:` setting. Items other than mappings are ignored. + runtime_function + Recover a function at a name that static analysis assigns to a submodule. Returns ------- @@ -898,8 +932,8 @@ def categorise_references( if name not in package.members: missing.append(name) continue - obj = package.members[name] try: + obj = _export_binding(package.members[name], runtime_function) kind = obj.kind except _ALIAS_ERRORS: categories["other"].append(name) diff --git a/great_docs/_reference/exports.py b/great_docs/_reference/exports.py index b9e1370e..26df1efd 100644 --- a/great_docs/_reference/exports.py +++ b/great_docs/_reference/exports.py @@ -127,7 +127,13 @@ def names(self, name: str) -> list[str] | None: file=sys.stderr, ) else: - exports = discovery.discover_exports(package, self.config, report=print) + check = probe.RendererCheck(normalized, report=print) + exports = discovery.discover_exports( + package, + self.config, + report=print, + runtime_function=check.exported_function if self.config.dynamic else None, + ) if exports is None: exports = self._dunder_all(name, normalized) @@ -208,11 +214,13 @@ def categorise(self, name: str, exports: list[str]) -> Categories: ] return categories + check = probe.RendererCheck(normalized, report=print) return discovery.categorise_exports( package, exports, - renderable=probe.RendererCheck(normalized, report=print), + renderable=check, report=print, + runtime_function=check.exported_function if self.config.dynamic else None, ) def sections(self, name: str) -> list[dict[str, Any]] | None: @@ -246,7 +254,12 @@ def sections(self, name: str) -> list[dict[str, Any]] | None: categories = discovery.empty_categories() else: try: - categories = discovery.categorise_references(package, reference_config) + check = probe.RendererCheck(package.path, report=print) + categories = discovery.categorise_references( + package, + reference_config, + runtime_function=check.exported_function if self.config.dynamic else None, + ) except BuildError as error: print(f"ERROR: {error}", file=sys.stderr) raise diff --git a/great_docs/_reference/probe.py b/great_docs/_reference/probe.py index 663648da..99c9d197 100644 --- a/great_docs/_reference/probe.py +++ b/great_docs/_reference/probe.py @@ -8,6 +8,7 @@ from __future__ import annotations +import inspect import re from typing import TYPE_CHECKING, Literal @@ -176,7 +177,7 @@ def detect_dynamic_mode( cycles += 1 except ImportError as error: report(f"Warning: {_import_warning(f'{package.path}:{name}', error)}") - except USER_CODE_ERRORS: + except (KeyError, *USER_CODE_ERRORS): pass if cycles: @@ -226,8 +227,6 @@ def __call__(self, path: str) -> bool: """ if self._imports is None: self._imports = self._import_package() - # Static analysis raises `KeyError` for a path it models nothing at. - errors = USER_CODE_ERRORS if self._imports else (KeyError, *USER_CODE_ERRORS) try: try: obj = get_object(path, dynamic=self._imports, loader=self._loader) @@ -237,16 +236,33 @@ def __call__(self, path: str) -> bool: self._report( f"Warning: {_import_warning(path, error)}; checking with static analysis instead" ) - try: - obj = get_object(path, loader=self._loader) - except KeyError: - return False + obj = get_object(path, loader=self._loader) _ = obj.members _ = obj.kind - except errors: + except (KeyError, *USER_CODE_ERRORS): return False return True + def exported_function(self, name: str) -> gf.Object | gf.Alias | None: + """ + Read a function the package exposes under a submodule's name + + Only inspect bindings in the package that already exist at runtime. + A missing binding does not require importing the candidate submodule. + """ + if self._imports is None: + self._imports = self._import_package() + if not self._imports: + return None + try: + package = import_project_module(self._module_name) + if not inspect.isroutine(getattr(package, name, None)): + return None + obj = get_object(f"{self._module_name}:{name}", dynamic=True, loader=self._loader) + return obj if obj.kind is gf.Kind.FUNCTION else None + except (KeyError, *USER_CODE_ERRORS): + return None + def _import_package(self) -> bool: """ Import the package, reporting a failure diff --git a/tests/test_reference_exports.py b/tests/test_reference_exports.py index 02ab80ce..5e1392d5 100644 --- a/tests/test_reference_exports.py +++ b/tests/test_reference_exports.py @@ -44,7 +44,7 @@ def test_finds_the_names_once(self, tmp_path, monkeypatch): exports = make_exports(_make_gd(tmp_path)) searches: list[str] = [] - def discover_exports(package, config, report): + def discover_exports(package, config, report, runtime_function): searches.append(package) return ["X"] @@ -63,7 +63,7 @@ def test_searches_again_after_finding_nothing(self, tmp_path, monkeypatch): monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock()) monkeypatch.setattr( "great_docs._reference.exports.discovery.discover_exports", - lambda package, config, report: next(found), + lambda package, config, report, runtime_function: next(found), ) monkeypatch.setattr( "great_docs._reference.exports.discovery.parse_dunder_all", @@ -83,7 +83,7 @@ def test_reads_the_project_package_init_when_discovery_finds_nothing( monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock()) monkeypatch.setattr( "great_docs._reference.exports.discovery.discover_exports", - lambda package, config, report: None, + lambda package, config, report, runtime_function: None, ) assert exports.names("mypkg") == ["Y"] @@ -128,7 +128,7 @@ def test_include_inherited_on_explicit_members(self, tmp_path, monkeypatch): monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock()) monkeypatch.setattr( "great_docs._reference.exports.discovery.categorise_references", - lambda package, reference: empty_categories(), + lambda package, reference, runtime_function: empty_categories(), ) result = make_exports(gd).sections("mypkg") assert result is not None @@ -158,7 +158,7 @@ def test_include_inherited_on_default_entry(self, tmp_path, monkeypatch): monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock()) monkeypatch.setattr( "great_docs._reference.exports.discovery.categorise_references", - lambda package, reference: empty_categories(), + lambda package, reference, runtime_function: empty_categories(), ) result = make_exports(gd).sections("mypkg") assert result is not None @@ -187,7 +187,7 @@ def test_plain_string_when_no_include_inherited(self, tmp_path, monkeypatch): monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock()) monkeypatch.setattr( "great_docs._reference.exports.discovery.categorise_references", - lambda package, reference: empty_categories(), + lambda package, reference, runtime_function: empty_categories(), ) result = make_exports(gd).sections("mypkg") assert result is not None diff --git a/tests/test_submodule_references.py b/tests/test_submodule_references.py index b37f3ba1..5e55762d 100644 --- a/tests/test_submodule_references.py +++ b/tests/test_submodule_references.py @@ -20,6 +20,7 @@ from great_docs._build.log import BuildLog from great_docs._build.steps import Skipped from great_docs._reference.discovery import categorise_references +from great_docs._reference.exports import Exports from tests.support import StubRemote, make_run, prepare_build_directory, write_config @@ -49,6 +50,93 @@ def package_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Pa sys.modules.pop(name, None) +@pytest.fixture +def shadowed_package(package_root: Path) -> Path: + package = package_root / "lookup_pkg" + (package / "__init__.py").write_text( + "from .exported import exported\nfrom .support import example\n" + ) + (package / "exported").mkdir() + (package / "exported" / "__init__.py").write_text( + "from .implementation import exported\n" + "from ..support import example\n" + "from ..support import example as module_only\n" + ) + (package / "exported" / "implementation.py").write_text( + 'def exported(value):\n """Static export documentation"""\n return value\n' + 'exported.__doc__ = "Runtime " + "export documentation"\n' + 'def attached():\n """Callable attribute documentation"""\n' + "exported.example = attached\n" + ) + (package / "support.py").write_text('__all__ = ["example"]\ndef example(): pass\n') + return package_root + + +def test_discovery_keeps_a_function_that_shadows_its_submodule(shadowed_package: Path) -> None: + write_config(shadowed_package, {"module": "lookup_pkg"}) + exports = Exports.make(GreatDocs(project_path=str(shadowed_package)).layout) + + names = exports.names("lookup_pkg") + assert names is not None + assert "exported" in names + categories = exports.categorise("lookup_pkg", names) + assert "exported" in categories["functions"] + assert "exported.exported" not in categories["functions"] + bare = [{"title": "API", "contents": ["exported"]}] + assert categorise_references(exports.package("lookup_pkg"), bare)["functions"] == ["exported"] + + +@pytest.mark.parametrize("dynamic", [False, True]) +def test_lookup_preserves_both_paths_to_a_shadowing_function( + shadowed_package: Path, dynamic: bool +) -> None: + for path in ["lookup_pkg:exported", "lookup_pkg:exported.exported"]: + export = get_object(path, dynamic=dynamic) + assert export.kind is griffe.Kind.FUNCTION + assert export.docstring is not None + expected = "Runtime export documentation" if dynamic else "Static export documentation" + assert export.docstring.value == expected + + module = get_object("lookup_pkg.exported", dynamic=dynamic) + assert module.kind is griffe.Kind.MODULE + + +def test_dynamic_lookup_keeps_the_module_parent_for_a_nested_alias(shadowed_package: Path) -> None: + obj = get_object("lookup_pkg:exported.module_only", dynamic=True) + assert obj.path == "lookup_pkg.exported.module_only" + + +def test_dynamic_lookup_prefers_an_existing_callable_attribute(shadowed_package: Path) -> None: + obj = get_object("lookup_pkg:exported.example", dynamic=True) + assert obj.kind is griffe.Kind.FUNCTION + assert obj.docstring is not None + assert obj.docstring.value == "Callable attribute documentation" + + +def test_init_keeps_a_function_reexported_via_a_wildcard(shadowed_package: Path) -> None: + package = shadowed_package / "lookup_pkg" + (package / "__init__.py").write_text( + "from .charts import chart\nfrom .support import example\n" + ) + (package / "charts").mkdir() + (package / "charts" / "__init__.py").write_text("from .chart import *\n") + (package / "charts" / "chart.py").write_text("def chart(): pass\n") + config = { + "module": "lookup_pkg", + "reference": [{"title": "API", "contents": ["chart"]}], + } + write_config(shadowed_package, config) + exports = Exports.make(GreatDocs(project_path=str(shadowed_package)).layout) + + names = exports.names("lookup_pkg") + assert names is not None + assert "chart" in names + assert "chart" in exports.categorise("lookup_pkg", names)["functions"] + sections = exports.sections("lookup_pkg") + assert sections is not None + assert sections[0]["contents"] == ["chart"] + + @pytest.mark.parametrize("name", ["bounds.censor", "nested.tools.censor"]) def test_dynamic_lookup_imports_only_the_requested_submodules( package_root: Path, name: str