-
-
Notifications
You must be signed in to change notification settings - Fork 33.3k
Closed
Labels
docsDocumentation in the Doc dirDocumentation in the Doc direasystdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytestsTests in the Lib/test dirTests in the Lib/test dir
Description
Bug report
Bug description:
If a dataclass has a subclass that is not itself a dataclass, is_dataclass() returns True on the subclass and its instances:
from dataclasses import dataclass, is_dataclass
@dataclass
class X:
y: int
class Z(X):
pass
print(is_dataclass(Z)) # True
print(is_dataclass(Z())) # TrueDocumentation of is_dataclass() for reference: https://docs.python.org/3.13/library/dataclasses.html#dataclasses.is_dataclass
Intuitively this seems wrong: Z is not itself a dataclass. In pyanalyze I wrote a replacement for is_dataclass() because I needed to check whether the exact class was a dataclass:
def is_dataclass_type(cls: type) -> bool:
try:
return "__dataclass_fields__" in cls.__dict__
except Exception:
return FalseChanging the CPython behavior might be impossible for compatibility reasons, but in that case, we should document and test this edge case.
cc @ericvsmith @carljm for dataclasses.
CPython versions tested on:
CPython main branch
Operating systems tested on:
macOS
Linked PRs
- gh-119260: Clarify is_dataclass Behavior for Subclasses in Documentation and Tests #119480
- [3.13] gh-119260: Clarify is_dataclass Behavior for Subclasses in Documentation and Tests (GH-119480) #119760
- [3.12] gh-119260: Clarify is_dataclass Behavior for Subclasses in Documentation and Tests (GH-119480) #119761
Metadata
Metadata
Assignees
Labels
docsDocumentation in the Doc dirDocumentation in the Doc direasystdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytestsTests in the Lib/test dirTests in the Lib/test dir