typing.NamedTuple

Tags:

파이썬의 typing, types를 보면 신기한 것들이 많이 추가되고 있다.

최근 @golbin 님으로부터 배운 것중 하나는 NamedTuple.

In [1]: from typing import NamedTuple

In [2]: class Employee(NamedTuple):
   ...:     name: str
   ...:     id: int
   ...:

In [3]: e = Employee('foo', 234)

In [4]: e
Out[4]: Employee(name='foo', id=234)

파이썬 3.7부터는 @dataclass라는 annotation으로 가능해진다.

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

혹시 -> float 부분이 뭐지 싶으신 분은 Type Hints를 참고하시길.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *