[Python] How to type-annotate write when subclassing io.RawIOBase, getting "Liskov...

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I want to type-annotate the write in a class that subclasses io.RawIOBase.

    I'm struggling to get anything other than Any to type check, which is frustrating, because I should be able to use a much more specific type here.

    The following doesn't type check unfortunately:

    from io import RawIOBase
    from typing import Union

    class BytesWrittenCounterIO(RawIOBase):
    def __init__(self) -> None:
    self.written: int = 0

    def write(self, b: Union[bytes, bytearray, memoryview]) -> int:
    n = len(b)
    self.written += n
    return n


    mypy 1.17.0 errors with:

    $ mypy counter.py
    counter.py:8: error: Argument 1 of "write" is incompatible with supertype "_RawIOBase"; supertype defines the argument type as "Buffer" [override]
    counter.py:8: note: This violates the Liskov substitution principle
    counter.py:8: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


    I know I can use Any but that's annoyingly broad. Is there any solution other than Any or # type: ignore[override]?

    Continue reading...

Compartilhe esta Página