The correct way to annotate a "file type" in Python

paul23 picture paul23 · Jan 19, 2017 · Viewed 7.4k times · Source

In modern versions of Ppython one can have static type analysis using function annotations, according to PEP 484. This is made easy through the typing module.

Now I'm wondering how I would give a "type hint" towards a "filestream".

def myfunction(file: FILETYPE):
    pass

with open(fname) as file:
    myfunction(file)

What would I insert as FILETYPE?

Using print(type(file)) returns <class '_io.TextIOWrapper'> which isn't clear at all.

Isn't there a generic "file" type?

Answer

Eugene Yarmash picture Eugene Yarmash · May 26, 2017

You can use typing.IO, typing.TextIO, and typing.BinaryIO to represent different types of I/O streams. To quote the documentation:

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 represent the types of I/O streams such
    as returned by open().

    These types are also accessible directly as typing.IO, typing.TextIO, and
    typing.BinaryIO.