flake8-pyi icon indicating copy to clipboard operation
flake8-pyi copied to clipboard

Warn for IO types like io.BytesIO

Open hugovk opened this issue 1 year ago • 4 comments

No warnings are raised for this:

from io import BytesIO


def open(fp: BytesIO):
    ...

Instead of the concrete io.BytesIO, this should probably be something more specific for what exactly the file-like object actually does, or possibly even typing.BinaryIO.

Similarly for other IO things.

Should flake8-pyi add some warnings in this area?

hugovk avatar Jan 22 '24 16:01 hugovk

In my experience, if a stub is annotated with BytesIO, it really needs a concrete type. I'd also discourage the use of BinaryIO, which – in my opinion – is a legacy type from before protocols existed.

srittau avatar Jan 22 '24 16:01 srittau

There's a large number of IO-related classes in the stdlib, and they all mean subtly different things; this can be pretty confusing. I think it's reasonable to have a lint flagging potential misuse of these, but there's an interesting question of how far we want to go here:

  • We could almost certainly emit a violation whenever io.BytesIO or io.StringIO is used as a parameter annotation. These are concrete classes, and you almost never want to mandate that people have to pass in instances of those specifically
  • Probably we could add TextIOWrapper to that list?
  • What about the many other io-module ABCs -- IOBase, RawIOBase, BufferedIOBase, FileIO, BufferedReader, BufferedWriter, BufferedRandom, BufferedRWPair, TextIOBase? Should we ban all of those in parameter annotations as well, on the basis that you should probably be using a user-defined protocol or, if you really need a broad ABC, a typing.py interface like typing.IO?

AlexWaygood avatar Jan 22 '24 17:01 AlexWaygood

Does this solve a practical problem? Has someone actually used a BytesIO argument type, without being aware of the meaning, when working on a project that uses this plugin? It seems like an unlikely combination to me.

Akuli avatar Jan 22 '24 20:01 Akuli

🙋

We're in the process of adding types to https://github.com/python-pillow/Pillow and have inadvertently used BytesIO in a number of places. We're not using this plugin yet, but I'll be adding it and fixing its other findings.

hugovk avatar Jan 22 '24 20:01 hugovk