python / python/cpython

Add `operator.identity`, the identity function

Open
#132,341 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

extension-modules pending stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

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

Linked PRs
  • gh-132342

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing _typing.idfunc and the proposed linked work in gh-132342, along with the issue's prior discussions about iterator APIs and typing decorators. Done means adding operator.identity in both Python and C, covering its single-argument behavior, and addressing the proposed replacement of _typing.idfunc.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.