Python Forum
The Drawbacks of @dataclass
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The Drawbacks of @dataclass
#1
Simple question: what are the drawbacks of @dataclass that was introduced in 3.7? I'm not real experienced in Python, but why not make all classes a dataclass and simplify (i.e. get rid of) the __init__()?
Reply
#2
I don't use dataclass yet, but __init__() is needed technically: it is the place where arbitrary code can be executed every time an instance is created. Arbitrary code can be much more than simply members initialization.
Reply
#3
I have a tutorial here
(Dec-02-2018, 08:36 AM)Gribouillis Wrote: what are the drawbacks of @dataclass that was introduced in 3.7?
I don't know if there any drawback is a new way to generate code for classes.
Example doing this,it's like writing 60 lines of code doing it without @dataclass.
Now is __init__(), __repr__(), __eq__(), __lt__(), __le__(), __gt__(), _ge__(), __setattr__(), __delattr__() generated.
from dataclasses import dataclass, field
from decimal import Decimal
 
@dataclass(order=True, frozen=True)
class Vehicle:
    kind: str = field(compare=False)
    name : str = field(compare=False)
    price: Decimal
I have not used @dataclass other than small test,i can see usefulness in some cases where need immutability,hashability and sorting.
Then a lot code is generated for you.
Reply
#4
I would say that generally there are not disadvantages. Technically, code generation is going to cost CPU and memory, but I doubt (unless you have a ton of dataclasses) that this would be an issue.

I've used them and really like them. Pro-tip: there's a __post_init__ method if you still need __init__ behavior in your dataclass :)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020