297

Is there any correct type hint to use for a file or file-like object in Python? For example, how would I type-hint the return value of this function?

def foo() -> ???:
    return open('bar')
0

3 Answers 3

358

Use either the typing.TextIO or typing.BinaryIO types, for files opened in text mode or binary mode respectively.

From the docs:

class typing.IO

Wrapper namespace for I/O stream types.

This defines the generic type IO[AnyStr] and aliases TextIO and BinaryIO for respectively IO[str] and IO[bytes]. These representing the types of I/O streams such as returned by open().

13
  • 5
    None of these seem to work for me: def f() -> IO: return open('test') gives "Expected type 'IO', got 'TextIOWrapper[str]' instead" in PyCharm.
    – user2124834
    Jun 24, 2017 at 10:04
  • 1
    Reproduced @Marein's issue in PyCharm community 2017.2: i.imgur.com/Ai4sVQl.jpg Dec 7, 2017 at 20:27
  • 3
    The documentation is a bit confusing, it indicates a deprecation, but i’m not entirely sure what is covered by it, the optimist interpretation that it’s only about the typing.io namespace, but i’m not keen on being too optimistic when programming.
    – Tshirtman
    Jun 16, 2021 at 16:42
  • 2
    @Tshirtman I think you can be a optimistic about this. I found this issue regarding the deprecation and it seems to be clearer about typing.io being the namespace to be deprecated because typing.io.BinaryIO and others also exist and were mostly used directly from the typing namespace, e.g., typing.BinaryIO.
    – mxmlnkn
    Jun 30, 2021 at 18:57
  • 1
    none of these types are recognized pyt plain-jane Python so I have no idea why anyone is suggesting these for function annotations.
    – user391838
    Oct 22, 2022 at 0:27
55

The short answer:

  • You need to be explicit. That is from typing import TextIO not just from typing import *.
  • Use IO to mean a file without specifying what kind
  • Use TextIO or BinaryIO if you know the type
  • You cannot currently specify it be opened for write or its encoding.

As an example:

from typing import BinaryIO

def binf(inf: BinaryIO):
    pass

with open('x') as f:
    binf(f)

gives an inspection error (in PyCharm) of Expected type 'BinaryIO', got 'TextIO' instead

1
  • Can you do an open without specifying a file to open? Jul 7, 2022 at 4:42
4

If you're annotating the type of a parameter, consider not using typing.IO, typing.TextIO, or typing.BinaryIO.

They risk being overly restrictive to the caller, because they include things that you often don't actually need, like .encoding and .newlines.

Instead, consider defining your own typing.Protocol. This lets you only require the parts of the "file-like" interface that you actually need.

So, for example, instead of doing this:

def foo(file_like: typing.TextIO) -> None:
    read_str = file_like.read()
    # ...

Consider doing this:

class TextFileLike(typing.Protocol):
    def read() -> str:
        ...

def foo(file_like: TextFileLike) -> None:
    read_str = file_like.read()
    # ...

Some Python core developers give this advice on https://github.com/python/typing/discussions/829.

These [typing.IO, typing.TextIO, and typing.BinaryIO] classes were meant to model the concept of a "file object", but when you start looking at how "file objects" are really used across the Python library system, you quickly realize that there's a ton of variation in what exactly you can do with them.

The downside to this typing.Protocol strategy is that it restricts your ability to change your implementation later on. For example, if you decide later that you want to call .readline() instead of .read(), and you didn't include .readline() in your original typing.Protocol, you'll need to make a breaking change to your interface. In other words, it's a tradeoff between being too restrictive to your callers up-front and causing API usability problems, or coupling the interface too tightly to your implementation and causing breaking changes down the line.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.