-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
typing.IO
and io.BaseIO
type hierarchies are incompatible
#6077
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The Python I/O classes violate the Liskov substitution problem and are a bit of a mess. They don't lend themselves well to typing, which lead to the introduction of the If you have any concrete suggestions on how to improve the typing classes in typeshed, please submit a PR so it can be evaluated and its impact can be judged, but I am closing this issue as I don't see anything actionable here. |
Python documentation for the
open()
builtin indicates thatopen()
returns types from theio.IOBase
hierarchy:Python documentation for
typing.IO[...]
suggests that objects returned by theopen()
builtin are of typetyping.IO[...]
.From this, I deduce that if I type a function as accepting either
typing.IO[typing.AnyStr]
orio.IOBase
, it should be able to accept any object returned fromopen()
. And following from this, I would assume that it should be possible to have an object that is of bothtyping.IO
andio.IOBase
type, because if objects that are oftyping.IO
type could not be oftyping.IOBase
type, and objects oftyping.IOBase
type could not be ofio.IOBase
type, then objects returned fromopen()
could not be in line with the documentation I quoted above.Given this, I would expect the following code to pass type checking without error:
However, when I run mypy on it, I get the following errors.
To further determine what is going wrong here, why something can't be of both
typing.IO
types andio.IOBase
types, I ran the following code through mypy, which again I would expect to pass without any errors:And for this code mypy reports the following errors, and specifically highlights the incompatibilities:
Summary
So in summary, I would expect the
io.IOBase
andtyping.IO[...]
hierarchies to be compatible, and all the code in here to pass mypy validation, but it does not. I'm not sure if there is a good explanation for why the two type hierarchies are incompatible.Practically, to work around this, I have to now type variables as
typing.Enum[typing.TextIO,io.TextIOBase]
if it should work withTextIO
like things. This is maybe partly due to some other issues (see python/mypy#11193, #6061, #6076), but definitely these incompatibilities do make things harder, and seem wrong to me.Versions
This issue is written for:
All code can be found here.
The text was updated successfully, but these errors were encountered: