Skip to content

tempfile issues #1780

Closed
Closed

Description

@srittau

I would expect the following to work:

from tempfile import TemporaryFile
from typing import BinaryIO


def make_temp() -> BinaryIO:
    return TemporaryFile()

But mypy 0.540 on Python 3.6 complains:

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.html BinaryIO is just an alias for IO[bytes], in which case the above should work, like the following code does:

from tempfile import TemporaryFile
from typing import IO


MyBinaryIO = IO[bytes]


def make_temp() -> MyBinaryIO:
    return TemporaryFile()

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

Activity

  1. srittau commented on Dec 11, 2017

    @srittau
    CollaboratorAuthor

    See also issue #434 for some historical context.

  2. gvanrossum commented on Dec 12, 2017

    @gvanrossum
    Member

    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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions