The correct type for the binary file object

I have the following functions defined using Python type hint:

from typing import BinaryIO

def do_something(filename: str):
    my_file = open(filename, "rb")
    read_data(my_file)

def read_data(some_binary_readable_thing: BinaryIO):
    pass

However, my IDE (PyCharm 2017.2) gives me the following warning on the line that I call read_file:

Expected type 'BinaryIO', got 'FileIO[bytes]' instead

What is the right type for me here? PEP484 defines it BinaryIOas a "simple subtype IO[bytes]." Does not match FileIO IO?

+4
source share
1 answer

This is similar to a bug in the Pycharm module or typing. From the module typing.py:

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

The documentation also indicates:

-, open().

, . FileIO.

from io import FileIO

def do_something(filename: str):
    my_file = open(filename, "rb")
    read_data(my_file)

def read_data(some_binary_readable_thing: FileIO[bytes]):
    pass
0

Source: https://habr.com/ru/post/1683998/


All Articles