r/Python • u/jpjacobpadilla • 3d ago
Tutorial The Inner Workings of Python Dataclasses Explained
Ever wondered how those magical dataclass decorators work? Wonder no more! In my latest article, I explain the core concepts behind them and then create a simple version from scratch! Check it out!
https://jacobpadilla.com/articles/python-dataclass-internals
(reposting since I had to fix a small error in the article)
13
u/DaelonSuzuka 3d ago
See also, the classic dataclasses talk by Raymond Hettinger:
8
u/yrubooingmeimryte 2d ago
This is a great example of how NOT to do a tech talk. It takes him nearly 20 minutes to actually start talking about anything and even when he finally gets to the point he still constantly gets sidetracked talking about unrelated shit that just distracts from the the topic.
3
5
u/JanEric1 3d ago
Is there any specific reason that is done like that? I feel like one should be able to do this without exec, but I haven't put the implementations side by side to compare.
14
u/FI_Stickie_Boi 3d ago
I believe the main reason is speed. attrs, the library dataclasses are based on, also do this, in order for the work to all be done during class creation, so that there's minimal overhead during "runtime" (ie. when you're instantiating classes, using methods, etc.) If you try and do this without eval/exec via decorators and all that, then you'll incur pretty significant runtime overhead because everytime you call a method, python will have to dig through multiple closures, which slows things down a lot.
3
1
1
u/magnomagna 2d ago
However, if there are arguments in the decorator, the dataclass function will be called
Just a small nitpick... better be more specific:
However, if there are only keyword-only arguments in the decorator, the dataclass function will be called
0
1
24
u/PurepointDog 3d ago
That felt so much hackier than I was expecting