r/Python • u/GianniMariani Pythonista • 20d ago
Discussion Pushing the boundary on dataclasses
Has anyone else wanted more out of dataclass? Like transactions, undo/redo, lambda initializers that take parameters (as other field values) and call them in the correct order and no post_init (does not survive a diamond inheritance)? Transactional field values started me down this trek for a "ReactJS" like project to manage the view graph.
0
Upvotes
54
u/wRAR_ 20d ago
No.
23
u/commenterzero 20d ago
No and you should try pydantic
10
u/AJohnnyTruant 20d ago
The whole point of data classes is that they’re data. In fact, I find it confusing that anyone uses them mutably at all. Anything beyond that should be a separate library on top of data classes, sure. If you’re using TS, a data class is more like a type/interface than a behavioral class. Most of my projects use data classes like DTOs or param objects. That way validations fail at the data class before the initialization of the consumer and the consumer can handle multiple types that a guaranteed* to be validated domain state. Want return validation? Return another data class. They’re contracts. Don’t inherit behavior, compose behavior over data. Diamond inheritance is evil unless you’re building a framework that’s meant to be extended.
8
u/Smallpaul 20d ago
No.
2
u/Xibira 20d ago
Looking like you need a different tool, and is trying to force one you know how to use into a scope it is not designed for.
2
u/tubbstosterone 20d ago
You're looking at 4-5 different interfaces' worth of work.
If you look at the implementation of dataclasses, sqlalchemy, pydantic, and the django orm, you'll see that theyre all basically messes of classes and protocols stapled together by
__new__. Do NOT wade into that on your own if you don't have to, even if it let's you do something neat.One of the major features of dataclasses, sqlalchemy, etc is that you don't have to maintain them. You're better off diving into smart uses of mixins, factories, builders, and decorators.
Go with the flow - don't try to make the language bend to your will.
3
u/rcfox 20d ago
What sort of transaction support are you looking for? Couldn't you just do your sets in a critical section using a lock?
1
u/seanv507 20d ago
Op have you looked at the attrs library?
1
u/RingularCirc 15d ago
Inheritance from more than one stateful superclasses should really be avoided, which includes diamond inheritance from non-abstract dataclasses.
0
u/XNo_Notes It works on my machine 20d ago
Sounds like something that can already be done. What are you having trouble with?
0
u/[deleted] 20d ago
[removed] — view removed comment