Search code examples
pythonpython-dataclasses

Is there a way to use a dataclass, with fields with defaults, with __slots__


I would like to put __slots__ on a dataclass with fields with defaults. When I try do that, I get this error:

>>> @dataclass
... class C:
...     __slots__ = ('x', 'y', )
...     x: int
...     y: int = 1
...     
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: 'y' in __slots__ conflicts with class variable

Is there a way to achieve this?


Solution

  • Since Python 3.10, you can enable the slots argument to dataclass decorator

    >>> from dataclasses import dataclass
    >>> 
    >>> @dataclass(slots=True)
    ... class C:
    ...     x: int
    ...     y: int = 1
    ... 
    >>> C.__slots__
    ('x', 'y')