[Python] How do I get the length of a WriteableBuffer?

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    Previous question: How do I add a type hint for a WriteableBuffer parameter?

    I'm trying to implement the readinto() method of a RawIOBase subclass with correct type hints.

    The version I have so far looks like this:

    from io import RawIOBase
    from typing import TYPE_CHECKING

    if TYPE_CHECKING:
    from _typeshed import WriteableBuffer

    class Reader(RawIOBase):
    def readinto(self, buf: WriteableBuffer):
    n = len(buf) # <-- this is not allowed
    # ... do something with n ...
    return super().readinto(buf)


    pyright complains about calling len() on buf:

    io.py:9:19 - error: Argument of type "WriteableBuffer" cannot be assigned to parameter "obj" of type "Sized" in function "len"
    "Buffer" is incompatible with protocol "Sized"
    "__len__" is not present (reportArgumentType)
    1 error, 0 warnings, 0 informations


    If I understand correctly WriteableBuffer is defined here, as:

    WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable


    All of these definitely have a defined length, except ctypes._CData, where only some subclasses define __len__ (e.g., arrays do, primitive values like int don't). But it seems the conclusion is that a WriteableBuffer just doesn't have a length, which is weird, because how should you write to it if you don't know its size?

    Is there a way to fix this code? Or should I just add a # type: ignore to the lines involving len(buf)?

    Continue reading...

Compartilhe esta Página