python / python/cpython

Add `operator.identity`, the identity function

Abierto
#132,341 8 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

extension-modules pending stdlib type-feature
Lenguaje dominante
Python
Estrellas
77.2k
Forks
36k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza revisando _typing.idfunc y el trabajo vinculado propuesto en gh-132342, junto con las discusiones previas del issue sobre las APIs de iteradores y los decoradores de typing. Se considera terminado añadir operator.identity tanto en Python como en C, cubrir su comportamiento con un solo argumento y abordar el reemplazo propuesto de _typing.idfunc.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
c, python
Área
backend
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.