Skip to content

is_dataclass() returns True for non-dataclass subclass of dataclass #119260

@JelleZijlstra

Description

@JelleZijlstra

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()))  # True

Documentation 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 False

Changing 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc direasystdlibStandard Library Python modules in the Lib/ directorytestsTests in the Lib/test dir

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions