Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions pdoc/docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@
from textwrap import indent
import warnings

AnyException = (SystemExit, GeneratorExit, Exception)
"""BaseException, but excluding KeyboardInterrupt.

Modules may raise SystemExit on import (which we want to catch),
but we don't want to catch a user's KeyboardInterrupt.
"""


@cache
def convert(docstring: str, docformat: str, source_file: Path | None) -> str:
Expand All @@ -32,17 +39,25 @@ def convert(docstring: str, docformat: str, source_file: Path | None) -> str:
"""
docformat = docformat.lower()

if any(x in docformat for x in ["google", "numpy", "restructuredtext"]):
docstring = rst(docstring, source_file)
try:
if any(x in docformat for x in ["google", "numpy", "restructuredtext"]):
docstring = rst(docstring, source_file)

if "google" in docformat:
docstring = google(docstring)

if "google" in docformat:
docstring = google(docstring)
if "numpy" in docformat:
docstring = numpy(docstring)

if "numpy" in docformat:
docstring = numpy(docstring)
if source_file is not None and os.environ.get("PDOC_EMBED_IMAGES") != "0":
docstring = embed_images(docstring, source_file)

if source_file is not None and os.environ.get("PDOC_EMBED_IMAGES") != "0":
docstring = embed_images(docstring, source_file)
except AnyException as e:
raise RuntimeError(
'Docstring processing failed for docstring=\n"""\n'
+ docstring
+ f'\n"""\n{source_file=}\n{docformat=}'
) from e

return docstring

Expand Down
18 changes: 5 additions & 13 deletions pdoc/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def walk_specs(specs: Sequence[Path | str]) -> list[str]:
modspec = importlib.util.find_spec(modname)
if modspec is None:
raise ModuleNotFoundError(modname)
except AnyException:
except pdoc.docstrings.AnyException:
warnings.warn(
f"Cannot find spec for {modname} (from {spec}):\n{traceback.format_exc()}",
stacklevel=2,
Expand Down Expand Up @@ -110,7 +110,7 @@ def parse_spec(spec: Path | str) -> str:
modspec = importlib.util.find_spec(spec)
if modspec is None:
raise ModuleNotFoundError
except AnyException:
except pdoc.docstrings.AnyException:
# Module does not exist, use local file.
spec = pspec
else:
Expand Down Expand Up @@ -218,18 +218,10 @@ def load_module(module: str) -> types.ModuleType:
Returns the imported module."""
try:
return importlib.import_module(module)
except AnyException as e:
except pdoc.docstrings.AnyException as e:
raise RuntimeError(f"Error importing {module}") from e


AnyException = (SystemExit, GeneratorExit, Exception)
"""BaseException, but excluding KeyboardInterrupt.

Modules may raise SystemExit on import (which we want to catch),
but we don't want to catch a user's KeyboardInterrupt.
"""


def iter_modules2(module: types.ModuleType) -> dict[str, pkgutil.ModuleInfo]:
"""
Returns all direct child modules of a given module.
Expand Down Expand Up @@ -315,7 +307,7 @@ def module_mtime(modulename: str) -> float | None:
try:
with mock_some_common_side_effects():
spec = importlib.util.find_spec(modulename)
except AnyException:
except pdoc.docstrings.AnyException:
pass
else:
if spec is not None and spec.origin is not None:
Expand Down Expand Up @@ -365,7 +357,7 @@ def invalidate_caches(module_name: str) -> None:
continue # some funky stuff going on - one example is typing.io, which is a class.
with mock_some_common_side_effects():
importlib.reload(sys.modules[modname])
except AnyException:
except pdoc.docstrings.AnyException:
warnings.warn(
f"Error reloading {modname}:\n{traceback.format_exc()}",
stacklevel=2,
Expand Down
9 changes: 9 additions & 0 deletions test/test_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ def test_rst_extract_options_fuzz(s):
assert not s or content or options


def test_convert_exception():
Copy link
Member

@mhils mhils Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a useful test because it tests unwanted behavior (we don't want any known cases of raising). Let's use pytest's monkeypatch to replace rst with a method that raises an exception, and then test with that as you currently do right now (with pytest.raises() is great).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahhh I see, that makes more sense.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the new commit look good now?

with pytest.raises(RuntimeError, match="Docstring processing failed"):
docstrings.convert(
"Parameters\n----------\n Parameter without a name or type",
"numpy",
None,
)


def test_rst_extract_options():
content = (
":alpha: beta\n"
Expand Down
2 changes: 1 addition & 1 deletion test/test_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_smoke(module):
try:
with pdoc.extract.mock_some_common_side_effects():
importlib.import_module(module)
except pdoc.extract.AnyException:
except pdoc.docstrings.AnyException:
pass
else:
try:
Expand Down