Type hint for a file or file-like object?

PythonType Hinting

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark AmeryView Question on Stackoverflow
Solution 1 - PythonWayne WernerView Answer on Stackoverflow
Solution 2 - PythonCharles MerriamView Answer on Stackoverflow