|
|
Subscribe / Log in / New account

PEP 557: Data Classes

From:  "Eric V. Smith" <eric-AT-trueblade.com>
To:  Python Dev <Python-Dev-AT-python.org>
Subject:  PEP 557: Data Classes
Date:  Fri, 8 Sep 2017 07:57:09 -0700
Message-ID:  <88ef501a-90de-a63d-03d3-7a9f15124aa0@trueblade.com>

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

Will automatically add these methods:

   def __init__(self, name: str, unit_price: float, quantity_on_hand: 
int = 0) -> None:
       self.name = name
       self.unit_price = unit_price
       self.quantity_on_hand = quantity_on_hand
   def __repr__(self):
       return 
f'InventoryItem(name={self.name!r},unit_price={self.unit_price!r},quantity_on_hand={self.quantity_on_hand!r})'
   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
   def __ne__(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
   def __lt__(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
   def __le__(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
   def __gt__(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
   def __ge__(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

Data Classes saves you from writing and maintaining these functions.

The PEP is largely complete, but could use some filling out in places. 
Comments welcome!

Eric.

P.S. I wrote this PEP when I was in my happy place.



to post comments


Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds