Skip to content

Looser type annotations for send_file() path_or_file argument #5776

@tvuotila

Description

@tvuotila

path_or_file argument of flask.helpers.send_file is typed as os.PathLike[t.AnyStr] | str | t.BinaryIO. This prevents passing some objects that are t.IO[bytes], but not t.BinaryIO. The underlyingwerkzeug.utils.send_file already allows t.IO[bytes] due to pallets/werkzeug#2209 since version 2.0.2.

Reproduction:

from tempfile import NamedTemporaryFile
from typing import IO

from flask.helpers import send_file


# The return type cannot be "BinaryIO" because "NamedTemporaryFile" is incompatible with it according to Mypy.
def some_function() -> IO[bytes]:
    file = NamedTemporaryFile()
    ...
    return file


file = some_function()
send_file(file)

Raises the following exception with Mypy 1.16.1.

error: Argument 1 to "send_file" has incompatible type "IO[bytes]"; expected "PathLike[str] | str | BinaryIO"  [arg-type]

I could simply change the return value of some_function to _TemporaryFileWrapper[bytes] or cast it to BinaryIO.
However, I would like to allow t.IO[bytes].

Side note: _TemporaryFileWrapper[bytes] conforms to PathLike[str] due to python/typeshed#7840. That is why it is accepted by flask.helpers.send_file.

Allowing t.IO[bytes] would be backwards compatible change as all t.BinaryIO are also t.IO[bytes].
Mypy Playground

Environment:

  • Python version: 3.12.11
  • Flask version: 3.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions