Skip to content

Support buffers in IO[bytes].write #9082

Closed
@dvarrazzo

Description

@dvarrazzo

Trying to annotate psycopg code in order to pass mypy check with disabled bytearray/memoryview promotion to bytes see branch mypy-0990.

Everything was smooth, except one questionable point:

from typing import IO, Union
from typing_extensions import TypeAlias

Buffer: TypeAlias = Union[bytes, bytearray, memoryview]

def write1(f: IO[bytes], data: Buffer) -> None:
    f.write(data)

Mypy 0.990 reports:

error: Argument 1 to "write" of "IO" has incompatible type "Union[bytes, bytearray, memoryview]"; expected "bytes"  [arg-type]

Same using BinaryIO instead of IO[bytes].

As far as I can see, a binary file supports any object supporting the buffer protocol (or maybe less than that? However, the three types in the union tested are definitely supported).

Declaring f: IO[Buffer] almost works: write() doesn't complain anymore, but IO does: Invalid type argument value for "IO".

Maybe something could be relaxed here?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions