Skip to content

Commit

Permalink
fix: Attributes without annotations cannot be dataclass parameters
Browse files Browse the repository at this point in the history
All dataclass parameters have annotations. When determining which of the attributes of dataclass are parameters, we explicitly check against that condition. This help us filter out obvious non-candidates that may otherwise fall through.

PR-297: #297
  • Loading branch information
has2k1 authored Jun 30, 2024
1 parent 72c8fc8 commit c9b2e09
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/griffe/extensions/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ def _dataclass_parameters(class_: Class) -> list[Parameter]:
if member.is_attribute:
member = cast(Attribute, member)

# All dataclass parameters have annotations
if member.annotation is None:
continue

# Attributes that have labels for these characteristics are
# not class parameters:
# - @property
Expand Down
24 changes: 24 additions & 0 deletions tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,27 @@ class Derived(Base):
assert param_b.docstring.value == "Parameter b"
assert param_c.docstring is None
assert param_d.docstring.value == "Parameter d"


def test_attributes_that_have_no_annotations() -> None:
"""Dataclass attributes that have no annotatations are not parameters."""
code = """
from dataclasses import dataclass, field
@dataclass
class Base:
a: int
b: str = field(init=False)
c = 3 # class attribute
@dataclass
class Derived(Base):
a = 1 # no effect on the parameter status of a
b = "b" # inherited non-parameter
d: float = 4
"""
with temporary_visited_package("package", {"__init__.py": code}) as module:
base_params = [p.name for p in module["Base"].parameters]
derived_params = [p.name for p in module["Derived"].parameters]
assert base_params == ["self", "a"]
assert derived_params == ["self", "a", "d"]

0 comments on commit c9b2e09

Please sign in to comment.