Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct type for binary file-like object

I have the following functions defined using Python type-hinting:

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 I invoke read_file:

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

What is the correct type for me to use here? PEP484 defines the BinaryIO as "a simple subtype of IO[bytes]". Does FileIO not conform to IO?

like image 983
DanielGibbs Avatar asked Aug 18 '17 22:08

DanielGibbs


People also ask

What is a binary file example?

Binary files can be used to store any data; for example, a JPEG image is a binary file designed to be read by a computer system. The data inside a binary file is stored as raw bytes, which is not human readable.

What does a binary file look like?

Structure. Binary files are usually thought of as being a sequence of bytes, which means the binary digits (bits) are grouped in eights. Binary files typically contain bytes that are intended to be interpreted as something other than text characters.

Which method is used to write the objects in a binary file?

dump(object , file_handler) - used to write any object to the binary file. Object=load(file_handler) - used to read object from the binary file.

What is in a binary file?

A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length. The content must be interpreted by a program or a hardware processor that understands in advance exactly how that content is formatted and how to read the data.


1 Answers

This looks like a bug in either Pycharm or typing module. From the typing.py module:

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

Also the documentation specifies:

These represent the types of I/O streams such as returned by open().

So it should work as stated. For now, a workaround would be to explicitly use 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
like image 148
Jorjon Avatar answered Oct 17 '22 04:10

Jorjon