Skip to content

Slots not checked if Self annotation is present #19331

Open
@alwaysmpe

Description

@alwaysmpe

Bug Report

When using a dataclass with slots=True or __slots__, if an argument to a function is annotated with Self (not necessarily the self argument), then assigning to an attribute not annotated in slots doesn't raise an error.

To Reproduce
Type check the below (playground).

from dataclasses import dataclass
from typing import Self

@dataclass(slots=True)
class Exp:
    x: int
    def foo(self) -> None:
        self.y = 1
    def bar(self, arg: Self) -> None:
        self.y = 1
    def baz(self: Self) -> None:
        self.y = 1

class Exp2:
    __slots__ = 'x',
    x: int
    def foo(self) -> None:
        self.y = 1
    def bar(self, arg: Self) -> None:
        self.y = 1
    def baz(self: Self) -> None:
        self.y = 1

Expected Behavior

All 3 invalid asignments to y would raise an error, dataclass or not.

Actual Behavior

Only the foo function raises an error for assigning to an attribute not in slots.

main.py:8: error: Trying to assign name "y" that is not in "__slots__" of type "__main__.Exp"  [misc]
main.py:18: error: Trying to assign name "y" that is not in "__slots__" of type "__main__.Exp2"  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.16.1
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-self-typesTypes for self

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions