You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
foo.py:6: error: Incompatible return value type (got "IO[Any]", expected "BinaryIO")
I am not sure where exactly the problem is. TemporaryFile returns IO[Any]. According to https://docs.python.org/3/library/typing.htmlBinaryIO is just an alias for IO[bytes], in which case the above should work, like the following code does:
But actually, typing from Python 3.6 derives BinaryIO from IO[bytes] and adds methods write() and __enter__().
Is this a an issue with the typing implementation of BinaryIO or with the documentation? In the latter case, should the return types of TemporaryFile et al. be changed to Union[BinaryIO, StringIO]?
Consider it a doc issue. Your code should use def make_temp() -> IO[bytes]: and then all is well.
FWIW TemporaryFile() cannot be typed properly using just the PEP 484 type system because it returns either IO[bytes] or IO[str] depending on the value of the mode parameter (the PEP 484 type system doesn't reason about values at all). In mypy we could fix this for constant mode arguments using a plugin, like we do for open(), but writing plugins is not a 100% solution (it doesn't help if the mode argument is a variable) and writing plugins is labor intensive. Hence the IO[Any].
Returning a Union is not great because that would force all callers to check the runtime return type using isinstance(). This is why in general we don't recommend returning unions (taking union parameters is fine though).
Activity
srittau commentedon Dec 11, 2017
See also issue #434 for some historical context.
gvanrossum commentedon Dec 12, 2017
Consider it a doc issue. Your code should use
def make_temp() -> IO[bytes]:and then all is well.FWIW TemporaryFile() cannot be typed properly using just the PEP 484 type system because it returns either IO[bytes] or IO[str] depending on the value of the mode parameter (the PEP 484 type system doesn't reason about values at all). In mypy we could fix this for constant mode arguments using a plugin, like we do for open(), but writing plugins is not a 100% solution (it doesn't help if the mode argument is a variable) and writing plugins is labor intensive. Hence the IO[Any].
Returning a Union is not great because that would force all callers to check the runtime return type using isinstance(). This is why in general we don't recommend returning unions (taking union parameters is fine though).