Dec-02-2018, 08:25 AM
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__()?
The Drawbacks of @dataclass
|
Dec-02-2018, 08:25 AM
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__()?
Dec-02-2018, 08:36 AM
(This post was last modified: Dec-02-2018, 08:36 AM by Gribouillis.)
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.
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: DecimalI 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.
Dec-02-2018, 06:49 PM
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 :) |
|