r/Python • • May 15 '18

The Ultimate Guide to Data Classes in Python 3.7

https://realpython.com/python-data-classes/
389 Upvotes

47 comments sorted by

View all comments

Show parent comments

9

u/PeridexisErrant May 16 '18

Yes, it's basically reinventing attrs badly.

Dataclasses are available without adding a dependency, but that's their only advantage. That's no small thing when it means the standard library can use them, but most other situations should use attrs.

9

u/masklinn May 16 '18 edited May 16 '18

That's actually mentioned in the dataclass PEP: https://www.python.org/dev/peps/pep-0557/#why-not-just-use-attrs

  • attrs moves faster than could be accommodated if it were moved in to the standard library.

  • attrs supports additional features not being proposed here: validators, converters, metadata, etc. Data Classes makes a tradeoff to achieve simplicity by not implementing these features.

For more discussion, see why not just attrs on github.

In the link, /u/glyph quite literally asks

Every aspect of the design here appears to be converging further in the direction of exact duplication of functionality available within attrs, except those which are features already on attrs's roadmap.

An important bit here is hynek's opinion on the subject: he'd find both importing-and-freezing (à la ipaddress) and importing-and-splitting (json/simplejson) undesirable, leaving only "versioned and upgradable", but while that's easy for a command-line utility (pip) it's quite a bit harder for a part of the standard library.

5

u/PeridexisErrant May 16 '18

I feel like we're trending towards another "/r/python hates everything" thread- and like I've contributed to that - so let's derail that now.

  • If you are asking "should I use dataclasses or attrs", the answer is always attrs.

  • BUT very many people are not in that position, and dataclasses will be a big improvement for many of them.

I strongly recomend that everyone in this thread go read Nick Coghlan's essay Considering Python's Target Audience - tldr, it's much bigger and more diverse than most of us imagine!

0

u/commissarg May 16 '18

dataclasses are not supposed to do run-time validation. attrs can do it.

0

u/[deleted] May 16 '18

[deleted]

2

u/commissarg May 16 '18

yes, but can't validate PEP 526 annotations yet.

2

u/PeridexisErrant May 16 '18

attrs does understand PEP 526 annotations (yet), and dataclasses don't validate them either.

2

u/commissarg May 16 '18 edited May 16 '18

pydantic can do the validation. It can be used in combination with attrs, if you turn off init in the decorator.

@attr.s(init=False, auto_attrs=True)
class C(BaseModel):
  c: int

should work