In modern versions of Python 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?
Advertisement
Answer
You can use typing.IO, typing.TextIO, and typing.BinaryIO to represent different types of I/O streams. To quote the documentation:
сlass typing.IO
class typing.TextIO
class typing.BinaryIOGeneric type
IO[AnyStr]and its subclassesTextIO(IO[str])andBinaryIO(IO[bytes])represent the types of I/O streams such as returned byopen().