[Python-Dev] PEP 557: Data Classes (original) (raw)
Eric V. Smith eric at trueblade.com
Fri Sep 8 11:01:34 EDT 2017
- Previous message (by thread): [Python-Dev] PEP 557: Data Classes
- Next message (by thread): [Python-Dev] PEP 557: Data Classes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Oops, I forgot the link. It should show up shortly at https://www.python.org/dev/peps/pep-0557/.
Eric.
On 9/8/17 7:57 AM, Eric V. Smith 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 unitprice: float quantityonhand: int = 0 def totalcost(self) -> float: return self.unitprice * self.quantityonhand Will automatically add these methods: def init(self, name: str, unitprice: float, quantityonhand: int = 0) -> None: self.name = name self.unitprice = unitprice self.quantityonhand = quantityonhand def repr(self): return f'InventoryItem(name={self.name!r},unitprice={self.unitprice!r},quantityonhand={self.quantityonhand!r})' def eq(self, other): if other.class is self.class: return (self.name, self.unitprice, self.quantityonhand) == (other.name, other.unitprice, other.quantityonhand) return NotImplemented def ne(self, other): if other.class is self.class: return (self.name, self.unitprice, self.quantityonhand) != (other.name, other.unitprice, other.quantityonhand) return NotImplemented def lt(self, other): if other.class is self.class: return (self.name, self.unitprice, self.quantityonhand) <_ _(other.name, other.unitprice, other.quantityonhand)_ _return NotImplemented_ _def _le_(self, other):_ _if other._class_ is self._class_:_ _return (self.name, self.unitprice, self.quantityonhand) <=_ _(other.name, other.unitprice, other.quantityonhand)_ _return NotImplemented_ _def _gt_(self, other):_ _if other._class_ is self._class_:_ _return (self.name, self.unitprice, self.quantityonhand) > (other.name, other.unitprice, other.quantityonhand) return NotImplemented def ge(self, other): if other.class is self.class: return (self.name, self.unitprice, self.quantityonhand) >= (other.name, other.unitprice, other.quantityonhand) 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.
- Previous message (by thread): [Python-Dev] PEP 557: Data Classes
- Next message (by thread): [Python-Dev] PEP 557: Data Classes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]