Skip to content

Commit 2729c22

Browse files
authored
fix: Don't return class variables as parameters of dataclasses
PR-253: #253
1 parent 6835ea3 commit 2729c22

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

src/griffe/extensions/dataclasses.py

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

83-
# Exclude @property and @cached_property attributes
84-
if "property" in member.labels:
83+
# Attributes that have labels for these characteristics are
84+
# not class parameters:
85+
# - @property
86+
# - @cached_property
87+
# - ClassVar annotation
88+
if "property" in member.labels or (
89+
# TODO: It is better to explicitly check for ClassVar, but
90+
# Visitor.handle_attribute unwraps it from the annotation.
91+
# Maybe create internal_labels and store classvar in there.
92+
"class-attribute" in member.labels
93+
and "instance-attribute" not in member.labels
94+
):
8595
continue
8696

8797
# Start of keyword-only parameters.

tests/test_dataclasses.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,17 +91,23 @@ def test_alias_proxies() -> None:
9191
assert name in alias_members
9292

9393

94-
def test_dataclass_properties() -> None:
95-
"""Don't return properties as parameters of dataclasses."""
94+
def test_dataclass_properties_and_class_variables() -> None:
95+
"""Don't return properties or class variables as parameters of dataclasses."""
9696
code = """
9797
from dataclasses import dataclass
9898
from functools import cached_property
99+
from typing import ClassVar
99100
100101
@dataclass
101102
class Point:
102103
x: float
103104
y: float
104105
106+
# These definitions create class variables
107+
r: ClassVar[float]
108+
s: float = 3
109+
t: ClassVar[float] = 3
110+
105111
@property
106112
def a(self):
107113
return 0
@@ -112,7 +118,7 @@ def b(self):
112118
"""
113119
with temporary_visited_package("package", {"__init__.py": code}) as module:
114120
params = module["Point"].parameters
115-
assert [p.name for p in params] == ["self", "x", "y"]
121+
assert [p.name for p in params] == ["self", "x", "y", "s"]
116122

117123

118124
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)