What is the correct way to subclass asyncio.StreamReader?
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 5.1k
- Forks
- 2.1k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 82
Descripción
#11755 changed the signature of asyncio.StreamReader.readuntil to make the separator argument take an internal type _ReaduntilBuffer that just has ... for its definition. This is confusing because inside the python 3.12 stdlib code this argument is already typed as bytes, which is the obvious choice. When I try to write my own subclass that takes bytes for the argument mypy complains I'm violating Liskov. Since this class is specifically designed as a base class that users would want to subclass themselves, it seems like there should be a way to do this that doesn't use internal types, no?
import asyncio
import typing
class StreamReaderWrapper(asyncio.StreamReader):
def __init__(self):
self._reader: asyncio.StreamReader | None = None
@typing.override
async def read(self, n: int = -1) -> bytes:
assert self._reader is not None
return await self._reader.read(n)
@typing.override
async def readline(self) -> bytes:
assert self._reader is not None
return await self._reader.readline()
@typing.override
async def readexactly(self, n: int) -> bytes:
assert self._reader is not None
return await self._reader.readexactly(n)
@typing.override
async def readuntil(self, separator: bytes = b'\n') -> bytes:
assert self._reader is not None
return await self._reader.readuntil(separator)
foo.py:4: error: Argument 1 of "readuntil" is incompatible with supertype "StreamReader"; supertype defines the argument type as "_ReaduntilBuffer" [override]
foo.py:4: note: This violates the Liskov substitution principle
foo.py:4: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
Note that using bytes | bytearray | memoryview as the type instead (taken from #11755) doesn't work either, same error
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Inspecciona el stub de asyncio.StreamReader.readuntil y la implementación de la stdlib de Python 3.12, empezando por la firma modificada por #11755. Reproduce el error de override con el StreamReaderWrapper proporcionado y mypy, y establece después una anotación pública que permita el caso de uso documentado de subclassing sin exponer un tipo interno inadecuado.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- developer-experience
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100