python / python/cpython

Make abstract/dunder methods positional-only.

Abierto
#135,312 18 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-typing type-feature
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Feature or enhancement

It would be nice if certain abstract methods / dunder methods would be defined with positional-only arguments, so that when one subclasses them an appropriate name can be chosen, or they can be defined positional-only in the subclass.[^1]

Code sample in pyright playground[^1]

from typing import overload
from collections.abc import Sequence

class MySequence[T](Sequence[T]):
    def __len__(self): return 0
    @overload
    def __getitem__(self, idx: int, /) -> T: ...
    @overload
    def __getitem__(self, idx: slice, /) -> Sequence[T]: ...
    def __getitem__(self, idx: int | slice, /) -> T | Sequence[T]:  # ❌ override
        return MySequence[T]()

In some cases, the stubs already fake that the argument is positional-only, such as for Container.__contains__:

Personally, I think only changing the stubs would be a pragmatic choice, but I was told by the maintainers that they believe this change should be done in Cpython first.

Backward Compatibility

  1. Changing non-abstract methods can potentially break user code. For example, this is currently legal code at runtime

    from collections.abc import Container.
    Container.__subclasshook__(C=list)  # True
    
  2. Changing the signature of abstract methods can introduce type-checker errors Code sample in pyright playground[^1]

    from collections.abc import Sequence
    def get(x: Sequence[float], index: int) -> float:
        return x.__getitem__(index=index)
    

With this in mind, I believe changing abstrac dunder methods to use positional only arguments should be relatively safe, as calling them directly with keyword is very uncommon, and at worst it will introduce type errors.

Personally, I'd also like so see methods like Container.__subclasshook__ use positional-only arguments, but I also understand if this is not feasible due to bc-conerns.

[^1]: Note that mypy special cases certain dunder methods, and yields different results than pyright on these examples

Has this already been discussed elsewhere?

https://github.com/python/typeshed/issues/14071

Linked PRs
  • gh-136324

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

Comienza con las definiciones citadas en Lib/_collections_abc.py y typeshed/stdlib/typing.pyi; después, revisa el PR enlazado gh-136324 y el issue relacionado de typeshed. Se considera terminado cuando las firmas acordadas de los métodos abstractos y dunder estén actualizadas en CPython y se hayan abordado las preocupaciones documentadas sobre la compatibilidad hacia atrás.

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

Evaluación

Stack tecnológico
python
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
4/5
Tiempo estimado
3-5 días
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.