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
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With