Skip to content

Classify __slots__ as class variables - #21886

Open
XuehaiPan wants to merge 2 commits into
python:masterfrom
XuehaiPan:fix-slots-classvar
Open

Classify __slots__ as class variables#21886
XuehaiPan wants to merge 2 commits into
python:masterfrom
XuehaiPan:fix-slots-classvar

Conversation

@XuehaiPan

Copy link
Copy Markdown

Python defines __slots__ on the class, but mypy currently classifies generated slots as instance variables. This produces an inconsistent override error when a subclass declares an explicitly typed empty __slots__:

from dataclasses import dataclass
from typing import ClassVar


@dataclass(slots=True)
class Base:
    x: float
    y: float


class Child(Base):
    __slots__: ClassVar[tuple[()]] = ()  # type: ignore[misc]

Before this change, the ignore is required to suppress:

Cannot override instance variable (previously declared on base class "Base") with class variable  [misc]

The same inconsistency applies to ordinary __slots__ and attrs-generated slots.

This PR classifies ordinary and plugin-generated __slots__ symbols as class variables while preserving the existing special __slots__ type and layout handling. It adds inheritance regression coverage for ordinary classes, dataclasses, and attrs classes.

Test plan:

  • Focused __slots__ regressions: 3 passed
  • check-slots.test, check-dataclasses.test, check-plugin-attrs.test, and check-classvar.test: 364 passed
  • python3 -m pre_commit run --all-files: all hooks passed

Mark ordinary and plugin-generated __slots__ symbols as class variables so inheritance does not produce spurious instance/class variable override errors.

Add regression coverage for ordinary classes, dataclasses, and attrs classes.
@github-actions

This comment has been minimized.

Keep __slots__ classified as a class variable for type checking, but do not attach it to native classes at runtime. Native classes use their own layout, and exposing inherited slots prevents compiled subclasses from being created.

Add a compiled inheritance regression that reproduces the CI failure.
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@A5rocks

A5rocks commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

Could you make an issue first? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants