Search code examples
pythonpython-3.xslotspython-dataclasses

How can dataclasses be made to work better with __slots__?


It was decided to remove direct support for __slots__ from dataclasses for Python 3.7.

Despite this, __slots__ can still be used with dataclasses:

from dataclasses import dataclass

@dataclass
class C():
    __slots__ = "x"
    x: int

However, because of the way __slots__ works it isn't possible to assign a default value to a dataclass field:

from dataclasses import dataclass

@dataclass
class C():
    __slots__ = "x"
    x: int = 1

This results in an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'x' in __slots__ conflicts with class variable

How can __slots__ and default dataclass fields be made to work together?


Solution

  • In Python 3.10+ you can use slots=True with a dataclass to make it more memory-efficient:

    from dataclasses import dataclass
    
    @dataclass(slots=True)
    class Point:
        x: int = 0
        y: int = 0
    

    This way you can set default field values as well.