Skip to content

[spec] Treat dataclass fields as instance-only attributes #2396

Backlog

Description

@randolf-scholz

Accessing dataclass fields through the class itself seems idiosyncratic and should arguably be disallowed by type checkers. Depending on how a field is defined, such access can produce inconsistent or even unsound behavior:

from dataclasses import dataclass, field

@dataclass
class Unslotted:
    attr: int = 0

@dataclass(slots=True)
class Slotted:
    attr: int = 0

@dataclass
class Factory:
    attr: list[int] = field(default_factory=list)

Unslotted.attr  # Returns the default value.
Slotted.attr  # Returns a member descriptor, not an int.
Factory.attr  # AttributeError at runtime.

Unslotted.attr = 123  # Does not change the constructor default.
Slotted.attr = 123  # Breaks the slot descriptor and instantiation.
Factory.attr = [123]  # Does not change the default factory.

When testing this snippet in multiplay, the only diagnostics reported are:

  • ty v0.0.115: rejects Slotted.attr = 123.
  • mypy v2.4.1: rejects both Slotted.attr and Slotted.attr = 123.
  • pyright v1.1.414, pyrefly v1.5.1, and zuban v0.11.1 report no errors.

Proposal

Treat dataclass fields as instance-only attributes for static typing purposes, rejecting both reads and assignments through the class itself.

That is, with respect to attribute access,

@dataclass
class Foo:
    attr: int = 0

should be treated like

class Foo:
    def __init__(self, attr: int = 0) -> None:
        self.attr: int = attr

Although dataclasses retain default values as class attributes under certain circumstances, this runtime behavior need not be reflected in the static interface.

In particular, switching between default and default_factory or enabling slots=True should arguably not affect whether a field is accessible through the class itself.

There is already precedent for this interpretation in the typing specification:

A Final dataclass field initialized in the class body is not a class attribute unless explicitly annotated with ClassVar.

The proposal would generalize this interpretation to ordinary dataclass fields.

Explicitly descriptor-typed fields may warrant separate consideration.

Related discussions

Activity

  1. added
    topic: other
    on Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: other

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions