Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What advantage is there to using attrs instead of the new dataclasses module in the standard library?


From "Why attrs"[1]:

PEP 557 added Data Classes to Python 3.7 that resemble attrs in many ways.

They are the result of the Python community’s wish to have an easier way to write classes in the standard library that doesn’t carry the problems of namedtuples. To that end, attrs and its developers were involved in the PEP process and while we may disagree with some minor decisions that have been made, it’s a fine library and if it stops you from abusing namedtuples, they are a huge win.

Nevertheless, there are still reasons to prefer attrs over Data Classes whose relevancy depends on your circumstances: attrs supports all mainstream Python versions, including CPython 2.7 and PyPy.

Data Classes are intentionally less powerful than attrs. There is a long list of features that were sacrificed for the sake of simplicity and while the most obvious ones are validators, converters, and __slots__, it permeates throughout all APIs.

On the other hand, Data Classes currently do not offer any significant feature that attrs doesn’t already have.

attrs can and will move faster. We are not bound to any release schedules and we have a clear deprecation policy.

One of the reasons to not vendor attrs in the standard library was to not impede attrs’s future developement.

[1] http://www.attrs.org/en/stable/why.html#data-classes


My own experience with dataclasses vs attrs:

`dataclass` primarily just provides a faster syntax for defining a simple struct-like class. For that alone I've found it tremendously useful.

At the same time, sometimes you do need more functionality around a "struct-like" class, that that's where attrs comes in (e.g. I use dataclasses/attrs to wrap configuration objects, which mostly just hold values but occasionally need a little more logic). Even then, I often end up extending the basic dataclass with some of my own common methods (e.g. serialization).


"They are the result of the Python community's wish to have an easier way to write classes in the standard library that doesn't carry the problems of namedtuples."

What are the problems of namedtuples?


IIRC, one of the biggest complaint is about performance. namedtuples are not known to be fast, but I think performance has gotten better in more recent Python versions.

This is just what I recall from reading PEPs, the email lists and release notes. My recollection may not be entirely accurate.


See the why-attrs link above.


You can gain a fair memory consumption improvement by using slotted classes. The standard namedtuple and attrs use them. However, dataclasses do not. So, you can have both ergonomics and slotted classes by using attrs.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: