Add `operator.identity`, the identity function
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Adding the identity function has come up a few times. Recently, it was noted on Discourse that the function may also be useful for deferring some runtime uses of typing imports, such as the @final and @overload decorators, where all that is needed at runtime is the identity function.
I propose to add operator.identity, a single-argument function returning the first argument. This would be implemented in both Python and C for performance, similarly to the existing _typing.idfunc, which it would replace.
Searching GitHub, this has previously been mentioned as useful for improving Python iterator performance, and comes up in discussions of API coherence for functions operating on iterators (e.g. groupby, filter, map), to avoid needing to special-case None. The topic last seems to have been substantivly discussed 17 years ago, in GH-46439 and GH-44652. There are over 300 instances of the single-argument identity function in the CPython tree, so the pattern is clearly prevalent. I would also argue that the typing use-case is both new since 2008 and compelling. Those who only use static type checkers pay a cost for the support injected by decorators such as @final or @overload which is not necessary. For such developers, a pattern such as the following would enable the benefits of static typing, whilst limiting the runtime cost as much as possible:
if TYPE_CHECKING:
from typing import final, overload
else
import operator
final = overload = operator.identity
A
Linked PRs
- gh-132342
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先检查现有的 _typing.idfunc 和 gh-132342 中提出的相关工作,以及 issue 之前关于迭代器 API 和 typing 装饰器的讨论。完成标准是同时在 Python 和 C 中添加 operator.identity,覆盖其单参数行为,并处理关于替换 _typing.idfunc 的提议。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- backend
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100