What is the correct way to subclass asyncio.StreamReader?
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 5.1k
- Forks
- 2.1k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 82
Description
#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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Inspectez le stub de asyncio.StreamReader.readuntil et l’implémentation de la stdlib de Python 3.12, en commençant par la signature modifiée par #11755. Reproduisez l’erreur d’override avec le StreamReaderWrapper fourni et mypy, puis définissez une annotation publique qui permette le cas d’utilisation documenté du subclassing sans exposer un type interne inadapté.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- developer-experience
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100