Skip to content

attrs & dataclasses false positive error with slots=True when subclassing from non-slots base class #15975

@Hnasar

Description

@Hnasar

Bug Report

With attrs.define(slots=True) and dataclass(slots=True), if the base class doesn't use __slots__ then mypy shouldn't error when assigning new attributes to the instance.

To Reproduce

import attrs
@attrs.define(slots=True)
class AttrEx(Exception):
    def __init__(self, other_exception: Exception) -> None:
        self.__traceback__ = other_exception.__traceback__  # should not error


import dataclasses
@dataclasses.dataclass(slots=True)
class DataclassEx(Exception):
    def __init__(self, other_exception: Exception) -> None:
        self.__traceback__ = other_exception.__traceback__  # should not error

class SlotsEx(Exception):
    __slots__ = ("foo",)
    def __init__(self, other_exception: Exception) -> None:
        self.__traceback__ = other_exception.__traceback__  # correctly doesn't error

https://mypy-play.net/?mypy=latest&python=3.11&gist=9abddb20dc0419557e8bc07c93e41d25

Expected Behavior

No error, since this is fine at runtime (and mypy correctly doesn't error for classes which manually define slots (and don't use attrs or dataclasses).

When inheriting from a class without slots, the dict and weakref attribute of the instances will always be accessible.
https://docs.python.org/3/reference/datamodel.html#slots

Actual Behavior

foo.py:7: error: Trying to assign name "__traceback__" that is not in "__slots__" of type "foo.AttrEx"  [misc]
foo.py:16: error: Trying to assign name "__traceback__" that is not in "__slots__" of type "foo.DataclassEx"  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.6.0+dev.d7b24514d7301f86031b7d1e2215cf8c2476bec0 (compiled: no) but this behavior is also present in 1.2 (if not earlier)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions