Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions Doc/library/dataclasses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,20 @@ Module contents
- *slots*: If true (the default is ``False``), :attr:`~object.__slots__` attribute
will be generated and new class will be returned instead of the original one.
If :attr:`!__slots__` is already defined in the class, then :exc:`TypeError`
is raised. Calling no-arg :func:`super` in dataclasses using ``slots=True`` will result in
the following exception being raised:
``TypeError: super(type, obj): obj must be an instance or subtype of type``.
The two-arg :func:`super` is a valid workaround. See :gh:`90562` for full details.
is raised.

.. warning::
Calling no-arg :func:`super` in dataclasses using ``slots=True``
will result in the following exception being raised:
``TypeError: super(type, obj): obj must be an instance or subtype of type``.
The two-arg :func:`super` is a valid workaround.
See :gh:`90562` for full details.

.. warning::
Having a base class with :meth:`~object.__init_subclass__` with parameters
Comment thread
sobolevn marked this conversation as resolved.
Resolved
when using ``slots=True`` will result in a :exc:`TypeError`.
Either use ``__init_subclass__`` with no parameters or use default values.
See :gh:`91126` for full details.

.. versionadded:: 3.10

Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3664,6 +3664,34 @@ class A(WithDictSlot): ...
self.assertEqual(A().__dict__, {})
A()

def test_slots_with_wrong_init_subclass(self):
Comment thread
sobolevn marked this conversation as resolved.
Resolved
class WrongSuper:
def __init_subclass__(cls, arg):
pass

with self.assertRaisesRegex(
TypeError,
"missing 1 required positional argument: 'arg'",
):
@dataclass(slots=True)
class WithWrongSuper(WrongSuper, arg=1):
pass

def test_slots_with_correct_init_subclass(self):
class CorrectSuper:
args = []
def __init_subclass__(cls, arg="default"):
cls.args.append(arg)

@dataclass(slots=True)
class WithCorrectSuper(CorrectSuper):
pass

# __init_subclass__ is called twice: once for `WithCorrectSuper`
# and once for `WithCorrectSuper__slots__` new class
# that we create internally.
self.assertEqual(CorrectSuper.args, ["default", "default"])


class TestDescriptors(unittest.TestCase):
def test_set_name(self):
Expand Down