A quick review of named tuples (standad and typed) and dataclasses.

From the Data Science from Scratch book.

namedtuple

Similar to dictionaries but

  • fields are named
  • values are immutable
from collections import namedtuple
import datetime
StockPrice = namedtuple('StockPrice', ['symbol', 'date', 'closing_price'])
type(StockPrice)
type
price = StockPrice('MSFT', datetime.date(2018, 12, 14), 106.03)
price
StockPrice(symbol='MSFT', date=datetime.date(2018, 12, 14), closing_price=106.03)
type(price)
__main__.StockPrice
price.symbol, price.date, price.closing_price
('MSFT', datetime.date(2018, 12, 14), 106.03)

NamedTuple

Simlar to namedtuple but

  • it is a class
  • fields have to be typed
  • as it is a class, it can have methods
from typing import NamedTuple
class StockPrice(NamedTuple):
    symbol: str
    date: datetime.date
    closing_price: float

    def is_high_tech(self) -> bool:
        return self.symbol in ['MSFT', 'GOOG', 'FB', 'AMZN', 'AAPL']
stockprice = StockPrice('MSFT', datetime.date(2019, 12, 14), 106.83)
stockprice
StockPrice(symbol='MSFT', date=datetime.date(2019, 12, 14), closing_price=106.83)
stockprice.is_high_tech()
True
StockPrice('TOOT', 12, 12).is_high_tech()
False

Dataclasses

Similar to NamedTuple but

  • fields are mutable
from dataclasses import dataclass
@dataclass
class StockPrice2:
    symbol: str
    date: datetime.date
    closing_price: float

    def is_high_tech(self) -> bool:
        return self.symbol in ['MSFT', 'GOOG', 'FB', 'AMZN', 'AAPL']
stockprice2 = StockPrice2('MSFt', datetime.date(2018, 12, 14), 106.03)
stockprice2
StockPrice2(symbol='MSFt', date=datetime.date(2018, 12, 14), closing_price=106.03)
stockprice2.closing_price /= 2
stockprice2.closing_price
53.015

For NamedTuple this does not work

stockprice.closing_price /= 2
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-7ab00711d514> in <module>
----> 1 stockprice.closing_price /= 2

AttributeError: can't set attribute