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?
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 aliasesTextIO
andBinaryIO
for
respectivelyIO[str]
andIO[bytes]
. These represent the types of I/O streams such
as returned byopen()
.These types are also accessible directly as
typing.IO
,typing.TextIO
, and
typing.BinaryIO
.