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')
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 aliasesTextIO
andBinaryIO
for respectivelyIO[str]
andIO[bytes]
. These representing the types of I/O streams such as returned byopen()
.
def f() -> IO: return open('test')
gives "Expected type 'IO', got 'TextIOWrapper[str]' instead" in PyCharm.
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
.
The short answer:
from typing import TextIO
not just from typing import *
.IO
to mean a file without specifying what kindTextIO
or BinaryIO
if you know the typeAs 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
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
, andtyping.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.