Type hint for a file or file-like object?

Mark Amery picture Mark Amery · Jul 25, 2016 · Viewed 28.8k times · Source

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

Answer

Wayne Werner picture Wayne Werner · Jul 25, 2016

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