Skip to content

Check file type annotations against open mode #2337

Closed
@flother

Description

@flother

I have a function argument whose type I want to limit to a file object that's open for binary reading — i.e. I want only an instance of io.BufferedReader as returned by open() when mode="rb".

from typing import IO


def parser(file_obj: IO[bytes]) -> None:
    pass

As I would expect, mypy runs without complaint on this code:

parser(open("example.bin", "rb"))

But it doesn't output an error for this:

parser(open("example.txt", "rt"))

In that case, I would want an error along the lines of Argument 1 to "parser" has incompatible type IO[str]; expected "IO[bytes]".

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions