主题: python
-
Python 3.10 结束支持后:查找运行时并重建环境
Python 上游生命周期表记载,Python 3.10 已于 2026年10月1日结束支持。应盘点服务、虚拟环境和镜像实际使用的解释器,再在受支持的分支上重建并测试各个应用。
-
设计 Python 命令行工具:argparse、main() 与退出码
将接口放入注册为控制台脚本的 main(argv) -> int 函数中,用 argparse 的 type 和 choices 做校验,遵循退出码惯例(0 表示成功,2 表示用法错误,1 表示其他失败,仅在有文档说明时才使用 sysexits 代码),将结果输出到 stdout、诊断信息输出到 stderr,并妥善处理 SIGINT 和管道中断。
-
为中位数、百分位数或比率用自助法(bootstrap)构建置信区间
对原始观测值做多次有放回重抽样,在每次重抽样上计算统计量,再从得到的分布中读出区间;这样就能为中位数、百分位数、比率,以及变体之间此类统计量的差值给出不确定性估计,而这些量原本没有教科书式的公式可用。报告时应写明方法、重抽样次数和样本量,并且对小样本的极端百分位数不要轻信这种做法给出的结果。
-
将 npm 与 PyPI 的发布身份绑定到获批的发布制品
OIDC 可信发布无需存储发布 token,但其安全性仍取决于已授权的工作流。应分离构建与发布、保护审批环节,并核验制品身份,不能把来源证明当成恶意软件检测结论。
-
使用生成输入进行基于属性的测试
基于属性的测试不依赖手工挑选的示例,而是声明一个不变条件,让库生成大量输入,并将失败案例缩减为最小反例。Hypothesis 是 Python 中这一方法的参考实现。
-
Python 上下文管理器:保证清理操作执行
with 语句在代码块前后调用 __enter__ 和 __exit__,使文件、锁和连接在发生异常时也能被释放;contextlib.contextmanager 可将生成器转换成上下文管理器。
-
让工具和读者都能有效使用的文档字符串
PEP 257 规定了文档字符串的位置和格式;采用一致的风格(Google 或 NumPy),包含单行概述、参数与返回值说明以及抛出的异常,便能让读者、编辑器和文档生成器有效使用它们。
-
浮点数:为什么 0.1 + 0.2 不等于 0.3
二进制浮点数只能近似表示大多数十进制小数,因此运算会累积舍入误差。应按容差比较、谨慎求和,金额和计数使用整数或十进制类型,并输出足够位数以便往返还原。
-
Loading YAML safely
Full YAML loaders can instantiate arbitrary objects from tagged nodes; always use a safe loader, pin the YAML version semantics, and validate the result against a schema before use.
-
Glob pattern dialects: what * and ** mean in .gitignore, .dockerignore, bash, Python and GitHub Actions
The same star and double-star characters mean different things depending on where the pattern is evaluated: a slash-less .gitignore pattern matches at every depth while the same line in .dockerignore only matches at the context root, bash's globstar recursion is opt-in, and Python's fnmatch is not even path-aware.
-
asyncio 何时有用,何时无益
asyncio 通过在 await 处挂起任务,在单个线程上运行大量受 I/O 限制的任务。它不会加速受 CPU 限制的代码,而协程中的阻塞调用会让整个事件循环停滞。
-
将自动格式化和代码检查作为团队约定
把布局交给格式化工具,把机械检查交给代码检查器,可以消除评审中的风格争论;EditorConfig、PEP 8 以及 Ruff 等工具展示了如何将约定编码到仓库中。
-
Protocol classes: structural typing for duck-typed Python
A typing.Protocol declares the methods and attributes a consumer needs; any object that has them satisfies the type without inheriting from it. Define protocols next to the code that depends on them, keep them minimal, and use runtime_checkable only where isinstance is really needed.
-
使用 tracemalloc 快照查找内存泄漏
尽早通过 PYTHONTRACEMALLOC 或 tracemalloc.start(nframe) 开始跟踪,在预热后和 N 次迭代后各取一份快照,过滤导入噪声,再用 compare_to(..., 'lineno') 找出内存大小随 N 成比例增长的代码行;切换到 'traceback' 分组即可查看调用者。
-
Money and other exact quantities: use Decimal, not float
Binary floating point cannot represent most decimal fractions exactly, so sums of prices drift; the decimal module provides exact decimal arithmetic with explicit rounding, and integers in minor units are an alternative.
-
为 Python 工作负载选择线程、进程或 asyncio
先判断热点路径的性质:等待 I/O 适合 asyncio(大量连接、异步库)或线程池(少量阻塞调用);纯 Python 的 CPU 工作需要进程或自由线程构建;释放 GIL 的原生代码可使用线程。限制每个池的规模,显式选择进程启动方式,并编写关闭流程。
-
Dataclasses for plain records
dataclasses generate __init__, __repr__ and equality from annotated fields; frozen dataclasses give immutable value objects, slots reduce memory, and field(default_factory=...) avoids shared mutable defaults.
-
At what workload does the free-threaded CPython build beat a process pool for a mixed I/O and CPU service?
Open question: the free-threaded build removes the GIL but adds single-threaded overhead and may fall back to the GIL when an unprepared extension is imported, while process pools pay for pickling and memory duplication; for which CPU-to-wait ratios, working sets and core counts does a thread pool on the free-threaded build deliver more throughput per core?
-
Attempting an exercise before reading its worked solution yields better one-month recall of a language feature than reading the solution first
Hypothesis: for an engineer learning a specific language feature, such as Python's match statement, working an exercise before seeing the worked solution leads to better delayed recall and transfer than studying the solution first and then working a similar exercise; a proposed within-person test with two features, two orders and a one-month delayed test, with no result claimed.
-
asyncio 取消:清理资源时不要吞掉 CancelledError
在被中断的路径上释放资源,同时让任务所有者仍能观察到取消。
机器可读: JSON