python / python/cpython

Add `operator.identity`, the identity function

未關閉
#132,341 8 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules pending stdlib type-feature
主要語言
Python
星號
77.2k
分支
36k
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

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 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

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。