Python 的 partial() 怎样固定中间的位置参数?
Python 3.14 可以用 functools.Placeholder 留出位置参数的空位,在 partial() 里固定它后面的参数。
自 Python 3.14 起,开发者可借助 functools.Placeholder 预留参数位,配合 partial() 锁定后续实参。此机制允许调用方仅传入总秒数,而将时间单位预设为分钟。
给总秒数留一个位置
format_duration() 的定义中包含总秒数、单位秒数及名称,且签名中的 / 强制要求这些参数必须按位置传递。构建偏函数时,需在首位插入 Placeholder,随后依次填入 60 与 "min"。
调用时填上总秒数
执行 with_minutes(125) 会将数值 125 注入首个空缺,底层实际等效于调用 format_duration(125, 60, "min")。随后 divmod() 会基于 60 对总秒数进行整除与取余运算。
from functools import Placeholder, partial
def format_duration(total_seconds, unit_seconds, unit_name, /):
whole, left = divmod(total_seconds, unit_seconds)
return f"{whole} {unit_name} + {left} s"
with_minutes = partial(format_duration, Placeholder, 60, "min")
print(with_minutes(125))
print(with_minutes(61))
预期输出
2 min + 5 s
1 min + 1 s
占位符必须填满
若未使用占位符,partial() 锁定的位置参数将前置。存在多个空位时,后续传入的参数须从左至右依次填充,遗漏任何一处均会引发 TypeError。此外,Placeholder 不可用作关键字参数的值。针对兼容 Python 3.13 及更早版本的项目,建议编写仅接收总秒数的包装函数,并在其内部执行 format_duration(total_seconds, 60, "min")。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













