Made for ThaiPy#95 lightning talk.
PEP 544 - Protocols: Structural subtyping (static duck typing)
Since Python 3.8.
- Static vs at runtime
- Duck Typing (the current main.py content)
- Use BaseExchange class
- Without raise NotImplementedError
- With raise NotImplementedError
- Use ABC
- Use ExchangeProtocol
Structural subtyping: an object that has certain properties is treated independently of its actual runtime class.
Nominal subtyping: based on inheritance.
class BinanceUSDFuturesExchange(BaseExchange):
- def get_symbol_price(self, symbol: str) -> Decimal:
+ def get_symbol_prices(self, symbol: str) -> Decimal:
class BaseExchange:
def get_symbol_price(self, symbol: str) -> Decimal:
pass
class BinanceSpotExchange(BaseExchange):
def get_symbol_price(self, symbol: str) -> Decimal:
response = requests.get(
f"https://api.binance.com/api/v3/avgPrice?symbol={symbol}"
)
return Decimal(response.json()["price"])
class BinanceUSDFuturesExchange(BaseExchange):
def get_symbol_prices(self, symbol: str) -> Decimal:
response = requests.get(
f"https://fapi.binance.com/fapi/v1/ticker/price?symbol={symbol}"
)
return Decimal(response.json()["price"])
class BaseExchange:
def get_symbol_price(self, symbol: str) -> Decimal:
raise NotImplementedError
class BaseExchange(ABC):
@abstractmethod
def get_symbol_price(self, symbol: str) -> Decimal:
pass
class ExchangeProtocol(Protocol):
def get_symbol_price(self, symbol: str) -> Decimal:
pass
EXCHANGES: Dict[ExchangeEnum, ExchangeProtocol] = {
ExchangeEnum.BINANCE_SPOT: BinanceSpotExchange(),
ExchangeEnum.BINANCE_USD_FUTURES: BinanceUSDFuturesExchange(),
}