4 ms·
I have a decorator to add support for slots: https://github.com/ericvsmith/dataclasses/blob/master/dataclass_tools.py https://github.com/ericvsmith/dataclasses/
by ericvsmith 6y ago
I have a decorator to add support for slots: https://github.com/ericvsmith/dataclasses/blob/master/dataclass_tools.py https://github.com/ericvsmith/dataclasses/blob/master/datacl... (although I'll admit I haven't tested it in a while).
The reason it's not an option by default is because it would be the one case where the decorator would have to return a new class, and I didn't want to do that on the first version. As it is, @dataclass just modifies an existing class. I might bite the bullet add a slots option, and we've had discussions on adding a language feature to automatically add slots to a class, based on annotations and maybe some other magic. If we did that, we wouldn't need to return a new class. But it's not a front-burner task for me.
- kzrdude 6y agoI believe this is the example where dataclasses could have supported __slots__ better with a metaclass? Thanks for working on dataclasses :) - as I said, it's my #1 new feature in Python.
- ericvsmith 6y agoMaybe that would have worked better with a metaclass. But still, I think not using a metaclass is the more flexible design. Maybe I'll add the "add_slots" behavior into the @dataclass decorator in 3.10, even though it would need to return a new class. At least it could be well documented, and I doubt it's a concern for most people. > Thanks for working on dataclasses :) - as I said, it's my #1 new feature in Python. I'm offended! I also wrote f-strings, but maybe that's not considered new anymore. In any event, you're welcome!
- kzrdude 6y agoMaybe the __slots__ discussion is not really that important - it's just convenience, and the regular old method of adding slots still works. So it's a minor thing. I have diligently converted to f-strings but it doesn't give me new expressibility like I feel dataclasses do, just convenience :)
- imcoconut 6y agofstrings and datclasses changed my life. thank you :)
- noitpmeder 6y agoI really appreciate it! Only issue I see is that it won't support inherited dataclasses where the base class already defines __slots__, but I should be able to hack together support.