Currently the draft PEP specifies and the code supports the optional ability to add __slots__. This is the one place where @dataclass cannot just modify the given class and return it: because __slots__ must be specified at class creation time, it's too late by the time the dataclass decorator gets control. The current approach is to dynamically generate a new class while setting __slots__ in the new class and copying over other class attributes. The decorator then returns the new class.
The question is: do we even want to support setting __slots__? Is having __slots__ important enough to have this deviation from the "we just add a few dunder methods to your class" behavior?
I see three options:
- Leave it as-is, with
@dataclass(slots=True) returning a new class.
- Completely remove support for setting
__slots__.
- Add a different decorator, say
@add_slots, which takes a data class and creates a new class with __slots__ set.
I think we should either go with 2 or 3. I don't mind not supporting __slots__, but if we do want to support it, I think it's easier to explain with a separate decorator.
@add_slots
@dataclass
class C:
x: int
y: int
It would be an error to use @add_slots on a non-dataclass class.
Currently the draft PEP specifies and the code supports the optional ability to add
__slots__. This is the one place where@dataclasscannot just modify the given class and return it: because__slots__must be specified at class creation time, it's too late by the time thedataclassdecorator gets control. The current approach is to dynamically generate a new class while setting__slots__in the new class and copying over other class attributes. The decorator then returns the new class.The question is: do we even want to support setting
__slots__? Is having__slots__important enough to have this deviation from the "we just add a few dunder methods to your class" behavior?I see three options:
@dataclass(slots=True)returning a new class.__slots__.@add_slots, which takes a data class and creates a new class with__slots__set.I think we should either go with 2 or 3. I don't mind not supporting
__slots__, but if we do want to support it, I think it's easier to explain with a separate decorator.It would be an error to use
@add_slotson a non-dataclass class.