Skip to content

Derived dataclass with slots generates exception calling super().__init__() #137237

Description

@tycarac

Bug report

Bug description:

The following code generates an exception where using a derived dataclass with slots. The expected behavior is for no exception to be raised for Derived3. The exception is:
Exception: super(type, obj): obj (instance of Derived3) is not an instance or subtype of type (Derived3).

from dataclasses import dataclass


# No dataclass
class Base1:
    b11: str

    def __init__(self, b11: str) -> None:
        self.b11 = b11


class Derived1(Base1):
    d11: str

    def __init__(self, b11: str, d11: str) -> None:
        super().__init__(b11)
        self.d11 = d11


@dataclass(slots=True)
class Base2:
    b21: str

    def __init__(self, b21: str) -> None:
        self.b21 = b21


# Derived dataclass without slots
@dataclass(slots=False)
class Derived2(Base2):
    d21: str

    def __init__(self, b21: str, d21: str) -> None:
        super().__init__(b21)
        self.d21 = d21


# Derived dataclass with slots
@dataclass(slots=True)
class Derived3(Base2):
    d31: str

    def __init__(self, b31: str, d31: str) -> None:
        super().__init__(b31)
        self.d31 = d31


# Code
s1 = 's1'
s2 = 's2'

D1 = Derived1(s1, s2)
print(f'D1: {str(D1)}')

D2 = Derived2(s1, s2)
print(f'D2: {str(D2)}')

try:
    D3 = Derived3(s1, s2)
    print(f'D3: {str(D3)}')
except Exception as e:
    print(f'Exception: {str(e)}')

The output I get is:

> python polymorphism.py
D1: <__main__.Derived1 object at 0x000001921C709160>
D2: Derived2(b21='s1', d21='s2')
Exception: super(type, obj): obj (instance of Derived3) is not an instance or subtype of type (Derived3).

PS: I am not sure why I get different string for the output of D1 and for D2, but I assume this is existing behavior (though weird).

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Activity

  1. StanFromIreland commented on Jul 30, 2025

    @StanFromIreland
    Member

    PS: I am not sure why I get different string for the output of D1 and for D2,

    D2 is a dataclass, which implements a nice __repr__ for you.

    I am unable to reproduce on main, I presume this has been fixed.

  2. tycarac commented on Jul 30, 2025

    @tycarac
    Author

    Thanks for the quick response. I was testing with Python version 3.13.5

  3. StanFromIreland commented on Jul 30, 2025

    @StanFromIreland
    Member

    Yes, this is now fixed and will be available in the next release.

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

    stdlibStandard Library Python modules in the Lib/ directorytopic-dataclassestype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions