PyCoder 513
百倍加速 Python API 原文: PyCoder’s Weekly - Issue #513 220222 Zoom.Quiet(大妈) 用时 13 分钟 完成快译 220222 Zoom.Quiet(大妈) 用时 37 分钟 完成格式转抄. 如何优化 Python API 服务器代码 100x VADIM MARKOVTSEV • Shared by Vadim Markovtsev Tricks we used to speed up calls to our analytical API written in Python: asyncio, SQLAlchemy, asyncpg, Cython plugins, improved data structures, and replaced some Pandas with NumPy. (是也乎: 在需要时… 反正都是些祖传手艺, 在电脑只有1K内存时… ) 在 Python 类中提供多个构造函数 REAL PYTHON Learn how to provide multiple constructors in your Python classes, including: checking argument types, using default argument values, writing class methods, and implementing single-dispatch methods. (是也乎: 模式匹配哪, 这是函式语言基本能力, 在 Python 中也可以模拟出来了… 基于 singledispatchmethod from datetime import date from functools import singledispatchmethod class BirthInfo: @singledispatchmethod def __init__(self, birth_date): raise ValueError(f"unsupported date format: {birth_date}") @__init__.register(date) def _from_date(self, birth_date): self.date = birth_date @__init__.register(str) def _from_isoformat(self, birth_date): self.date = date.fromisoformat(birth_date) @__init__.register(int) @__init__.register(float) def _from_timestamp(self, birth_date): self.date = date.fromtimestamp(birth_date) def age(self): return date.today().year - self.date.year ) ...