mypy - unable to use BufferedIOBase in type signature

Viewed 96

I have the following code

import io

def reader(byte_stream: io.BufferedIOBase):
    ...

reader(open("./README.md", "rb"))

When I run this file through mypy, I get the following type error:

subclass.py:6:8: error: Argument 1 to "reader" has incompatible type "BinaryIO"; expected "BufferedIOBase"  [arg-type]
    reader(open("./README.md", "rb"))
           ^
Found 1 error in 1 file (checked 1 source file)

This should not be an error though, as BinaryIO inherits from BufferedIOBase, which I have verified here:

isinstance(open("./README.md", "rb"), io.BufferedIOBase)  # True

So, what is wrong with my type signature?

1 Answers

I don't know exactly why the class is incompatible with the type hint, but the easy fix is to use the type hint in your signature. (It's even documented as representing the type of values returned by open.)

def reader(byte_stream: typing.BinaryIO):
    ...
Related