[Python-Dev] PEP 557: Data Classes

Nick Coghlan ncoghlan at gmail.com
Fri Sep 8 13:37:12 EDT 2017


On 8 September 2017 at 07:57, Eric V. Smith <eric at trueblade.com> wrote:
> I've written a PEP for what might be thought of as "mutable namedtuples with
> defaults, but not inheriting tuple's behavior" (a mouthful, but it sounded
> simpler when I first thought of it). It's heavily influenced by the attrs
> project. It uses PEP 526 type annotations to define fields. From the
> overview section:
>
> @dataclass
> class InventoryItem:
>     name: str
>     unit_price: float
>     quantity_on_hand: int = 0
>
>     def total_cost(self) -> float:
>         return self.unit_price * self.quantity_on_hand

Very nice!

>   def __eq__(self, other):
>       if other.__class__ is self.__class__:
>           return (self.name, self.unit_price, self.quantity_on_hand) ==
> (other.name, other.unit_price, other.quantity_on_hand)
>       return NotImplemented

My one technical question about the PEP relates to the use of an exact
type check in the comparison methods, rather than "isinstance(other,
self.__class__)".

I think I agree with that decision, but it isn't immediately obvious
that the class identity is considered part of the instance value for a
data class, so if you do:

    @dataclass
    class BaseItem:
        value: Any

    class DerivedItem:
        pass

Then instances of DerivedItem *won't* be considered equivalent to
instances of BaseItem, and they also won't be orderable relative to
each other, even though "DerivedItem" doesn't actually add any new
data fields.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list