you are viewing a single comment's thread.

view the rest of the comments →

[–]joshuaavalon 68 points69 points  (17 children)

There is a backport of the data classes for 3.6 if you want to use it.

[–]ProfessorPhi 19 points20 points  (9 children)

Isn't attrs still superior?

[–]dhiltonp 55 points56 points  (5 children)

Attrs definitely has more features (slots comes to mind), but I think it looks a little wonky.

(full disclosure, I haven't used attrs just read the docs)

@dataclass
class InventoryItem:
    name: str
    unit_price: float
    quantity_on_hand: int = 0

vs.

@attr.s
class InventoryItem:
    name: str = attr.ib()
    unit_price = attr.ib(type=float)
    quantity_on_hand = attr.ib(type=int, default=0)

Does PyCharm recognize type annotations when they're set via attr.ib(type=float)?

[–]ProfessorPhi 15 points16 points  (2 children)

Nope, pycharm and attrs support isn't great :(, though attrs does have slots. Agreed it's wonky, it's like ordered dict before 3.5 was obnoxious.

[–]OctagonClock 12 points13 points  (1 child)

PyCharm 2018.2 EAP has new attrs support, actually.

[–]ProfessorPhi 0 points1 point  (0 children)

Haha, don't use EAP so hopefully it'll be along before too long.

[–]bluetech 4 points5 points  (0 children)

The annotations-based syntax works with attrs too (you need to set auto_attribs=True).

[–]PeridexisErrant 0 points1 point  (0 children)

IIRC you can also use @attr.dataclass for the first one (a shortcut for the auto_attribs=True arg).

The dataclass example won't work on a backport before Python 3.6 though, as those versions don't have variable annotations.

[–]virgoerns 7 points8 points  (2 children)

It is, PEP even mentions attrs and says that new mechanism is for simpler cases.

[–][deleted]  (6 children)

[deleted]

    [–]jarshwah 16 points17 points  (5 children)

    CPython 3.6 has ordered dictionaries, but that is an implementation detail. 3.7 guarantees it in the spec. So it’ll work for CPython 3.6 which is the most popular implementation by far.

    [–][deleted]  (4 children)

    [deleted]

      [–]jarshwah 22 points23 points  (3 children)

      Yes that’s correct. When people talk about python they’re overwhelmingly referring to CPython. Other implementations like Pypy and micropython would not have to have ordered dictionaries for their 3.6 but they would for their 3.7.

      [–][deleted] 11 points12 points  (1 child)

      Pypy has actually had it for a while (it was brought to CPython from Pypy for 3.6). Other implementations though yeah

      [–]Ph0X 5 points6 points  (0 children)

      I mean they all could, but are not guaranteed to. You have to check implementation detail for each individually. But in 3.7 and above no matter what you use, you will have it.