Skip to content

Commit 3981031

Browse files
committed
Merge branch 'main' of github.com:mkdocstrings/griffe
2 parents 1c92f5f + ea299dc commit 3981031

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

src/griffe/extensions/dataclasses.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ def _dataclass_parameters(class_: Class) -> list[Parameter]:
8080
if member.is_attribute:
8181
member = cast(Attribute, member)
8282

83+
# All dataclass parameters have annotations
84+
if member.annotation is None:
85+
continue
86+
8387
# Attributes that have labels for these characteristics are
8488
# not class parameters:
8589
# - @property

src/griffe/finder.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -439,8 +439,15 @@ def _handle_pth_file(path: Path) -> list[_SP]:
439439
# No item is added to sys.path more than once.
440440
# Blank lines and lines beginning with # are skipped.
441441
# Lines starting with import (followed by space or tab) are executed.
442-
directories = []
443-
for line in path.read_text(encoding="utf8").strip().replace(";", "\n").splitlines(keepends=False):
442+
directories: list[_SP] = []
443+
try:
444+
# It turns out PyTorch recommends its users to use `.pth` as the extension
445+
# when saving models on the disk. These model files are not encoded in UTF8.
446+
# If UTF8 decoding fails, we skip the .pth file.
447+
text = path.read_text(encoding="utf8")
448+
except UnicodeDecodeError:
449+
return directories
450+
for line in text.strip().replace(";", "\n").splitlines(keepends=False):
444451
line = line.strip() # noqa: PLW2901
445452
if _re_import_line.match(line):
446453
editable_module = path.parent / f"{line[len('import'):].lstrip()}.py"

tests/test_dataclasses.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,3 +421,27 @@ class Derived(Base):
421421
assert param_b.docstring.value == "Parameter b"
422422
assert param_c.docstring is None
423423
assert param_d.docstring.value == "Parameter d"
424+
425+
426+
def test_attributes_that_have_no_annotations() -> None:
427+
"""Dataclass attributes that have no annotatations are not parameters."""
428+
code = """
429+
from dataclasses import dataclass, field
430+
431+
@dataclass
432+
class Base:
433+
a: int
434+
b: str = field(init=False)
435+
c = 3 # class attribute
436+
437+
@dataclass
438+
class Derived(Base):
439+
a = 1 # no effect on the parameter status of a
440+
b = "b" # inherited non-parameter
441+
d: float = 4
442+
"""
443+
with temporary_visited_package("package", {"__init__.py": code}) as module:
444+
base_params = [p.name for p in module["Base"].parameters]
445+
derived_params = [p.name for p in module["Derived"].parameters]
446+
assert base_params == ["self", "a"]
447+
assert derived_params == ["self", "a", "d"]

0 commit comments

Comments
 (0)