python / python/cpython

"typing.BinaryIO" missing "readinto" method

Open
#133,492 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-typing type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

typeing.BinaryIO is completely missing the readinto method. All binary mode return values of open support the readinto method, and the lack of it on the BinaryIO type makes type-hinting difficult when using this method. One could try to use io.RawIOBase | io.BufferedIOBase but this looses the fact that the result of open has a name property. This has been brought up in python/typing#659 and python/typeshed#2166.

Furthmore, the write method in BinaryIO is declared to only be compatible with Union[bytes, bytearray] when it should be anything that satisfies collections.abc.Buffer.

I propose that BinaryIO should look something more like:

class BinaryIO(IO[bytes]):
    """Typed version of the return of open() in binary mode."""

    __slots__ = ()

    @abstractmethod
    def readinto(self, b: collections.abc.Buffer) -> int:
        pass

    @abstractmethod
    def write(self, s: collections.abc.Buffer) -> int:
        pass

    @abstractmethod
    def __enter__(self) -> 'BinaryIO':
        pass
CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the typing.BinaryIO definition and compare it with the binary-mode return values of open(), focusing on the proposed readinto and Buffer-compatible write signatures. Verify that BinaryIO still exposes the name property and that the updated typing behavior is covered by the relevant existing tests; the issue does not name a specific file or test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.