python / python/typing

Allow Self or Self-like type arguments for generics

Abierto
#2,276 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

from contextlib import AbstractContextManager

class ManagerA(AbstractContextManager):
    def __init__(self, x: int) -> None:
        self._x = x
    def __enter__(self) -> int:
        return self._x

This can raise type check errors because AbstractContextManager is a generic type, and this code omits the type argument. Fair enough, and easy to fix:

from contextlib import AbstractContextManager

class ManagerA(AbstractContextManager[int]):
    def __init__(self, x: int) -> None:
        self._x = x
    def __enter__(self) -> int:
        return self._x

But what if we are not overriding the __enter__ method? Consider this example:

from contextlib import AbstractContextManager

class ManagerB(AbstractContextManager):
    def __init__(self, x: int) -> None:
        self._x = x
    # Other methods are defined, but __enter__ is not overridden

In this case, there is no great way to accurate type annotate it in order to reflect the fact that the __enter__ method always returns the object that it was called on (which is the default implementation of the __enter__ method in AbstractContextManager.

If we were willing to mark this class as final, then we could annotate it as:

class ManagerB(AbstractContextManager["ManagerB"]):

And that would work. But if we want to be able to subclass it, then this would no longer be accurate. Consider:

from contextlib import AbstractContextManager
from types import TracebackType
from typing import Type

class ManagerB(AbstractContextManager["ManagerB"]):
    def __init__(self, x: int) -> None:
        self._x = x

    # Other methods are defined, but __enter__ is not overridden

    def __exit__(
            self, exc_type: Type[BaseException] | None,
            exc_val: BaseException | None,
            exc_tb: TracebackType | None) -> bool | None:
        return None

class SubManager(ManagerB):
    def harf(self) -> None:
        print("harf")

with SubManager(1) as subman:
    subman.harf()

This runs fine, but the type checker will rightly complain. The annotations indicate that subman should be of type ManagerB, but ManagerB has no harf attribute.

It feels like it would be appropriate to use:

class ManagerB(AbstractContextManager[Self]):

But Self is not allowed to be used in this context.

The feature I would like to see is some way to accurately handle non-final subclasses of AbstractContextManager that do not overwrite the __enter__ method (or that overwrite it but still return self).

Obviously this issue applies generally to generics -- this is just an obvious example since the Python implementation of that class makes it impossible to type annotate many of its subclasses. But ideally any solution would apply generally to generics -- essentially giving a way to use Self (or something Self-like) as the type argument for a generic.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

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 los ejemplos de AbstractContextManager y la restricción indicada sobre el uso de Self como argumento de tipo genérico. Compara el comportamiento deseado para ManagerB y SubManager con las reglas actuales para Self, la herencia y los argumentos de tipo genérico. Se considera terminado cuando una solución general infiere correctamente la subclase concreta y conserva el comportamiento correcto para los métodos enter sobrescritos o heredados.

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

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.