python / python/typeshed

What is the correct way to subclass asyncio.StreamReader?

オープン
#12,423 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

topic: asyncio
主要言語
Python
スター
5.1k
フォーク
2.1k
平均マージ
1日 19時間
マージ済み PR(30日)
82

説明

#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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

asyncio.StreamReader.readuntil のスタブと Python 3.12 の stdlib 実装を、#11755 で変更されたシグネチャから調査してください。提供された StreamReaderWrapper と mypy を使って override エラーを再現し、その後、不適切な内部型を公開せずに、文書化されたサブクラス化のユースケースを許可するパブリックアノテーションを確立してください。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
developer-experience
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。