Open srittau opened 2 years ago
PR: #92878
PR: #92877
I think you mean #92878 -- this is #92877 :)
PR: #92877
I think you mean #92878 -- this is #92877 :)
I'm not sure what you mean. 😇
How is IO[Text]
a "legacy" feature and why should it be used "sparingly"? In my talk I advise the opposite: that users should typically avoid "FileLike" protocols that specify a subset of functionality. I do it because:
I'm curious whether we can come up with a similar list of arguments against using IO[Text]
and in favor of custom protocols.
IO
and its subclasses have several, quite major problems:
IO
is expected.IO
and BinaryIO
/TextIO
is a bit arbitrary, and it's often not really clear whether to annotate something with the former or the latter.All of these things make it quite hard to use custom file-like classes with type checking. Even using file-like objects from libraries becomes hard, because they usually don't implement methods like isatty()
or truncate()
. Often they are read-only, meaning they won't implement write()
. These are some of the reasons why we're moving away from those classes - at least for argument types - in typeshed.
I believe the best way forward is to create two new protocols Reader
and Writer
(or similar) with a small set of methods that are actually used. I'm thinking along the lines of read()/write()
, close()
, seek()/tell()
, __iter__
and readline()
for readers. (List not final.) This would make it easy for application and library authors to use these in type annotations, but has none of the problems above. (Except maybe overspecification.) If the supported methods are chosen carefully, it also allows forward compatibility to a certain degree. More difficult cases could use these protocols as base protocols.
Documentation
typing.IO
and subclassestyping.TextIO
andtyping.BinaryIO
are a bit of a legacy feature and should be used sparingly. We should document better alternatives. I'm preparing a PR with some suggestions.(Cc @gvanrossum @JelleZijlstra @AlexWaygood)