"""Transaction class implementation.""" from __future__ import annotations from time import strftime, strptime, gmtime from typing import Optional, List __all__ = ["Transaction", "TYPE_INCOME", "TYPE_OUTCOME", "TIME_FORMAT"] TYPE_INCOME = "in" TYPE_OUTCOME = "out" TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" class Transaction: """An object that holds a transaction. Arguments: - coins -- a list of numbers represent count for each face value; - direction -- is this income or outcome. Takes TYPE_INCOME or TYPE_OUTCOME; - timestamp -- date and time formated accordingly to TIME_FORMAT.""" def __init__(self, coins: List[int], direction: str = TYPE_INCOME, timestamp: Optional[str] = None) -> None: self.coins = coins if direction in [TYPE_INCOME, TYPE_OUTCOME]: self.direction = direction else: raise ValueError(f"Direction may only be" f"'{TYPE_INCOME}' or '{TYPE_OUTCOME}'") if timestamp is None: self.timestamp = strftime(TIME_FORMAT, gmtime()) else: try: strptime(timestamp, TIME_FORMAT) except ValueError: raise ValueError(f"Timestamp {timestamp} has wrong format. " f"The right one is '{TIME_FORMAT}''") self.timestamp = timestamp @staticmethod def from_string(transaction: str) -> Transaction: """Makes a Transaction object from its string output.""" timestamp, direction, coins = transaction.split() coins = list(map(int, coins.split(","))) return Transaction(coins, direction, timestamp) def __str__(self) -> str: return f"{self.timestamp} {self.direction} " \ f"{','.join(str(c) for c in self.coins)}" def __repr__(self) -> str: return f"Transaction(coins={self.coins!r}," \ f"direction={self.direction!r}, timestamp={self.timestamp!r})"