Description
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