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
?
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