-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[PYI] Suggest using typing.IO[bytes]
instead of io.BytesIO
.
#15532
Comments
We've had a request for this before at flake8-pyi: see PyCQA/flake8-pyi#463. I think it's a reasonable request; I agree that annotating a parameter with I'd be hesitant to recommend |
It's unfortunate that the standard library doesn't provide a sensible So if the library author does not want to introduce an extra Protocol, then |
I'd be okay with an error message that said something like "Use |
Another aspect of this is what to recommend for branching against def save(name_or_buffer: str | os.PathLike[str] | io.BytesIO, data) -> None:
if isinstance(name_or_buffer, io.BytesIO):
... # use the `.write()` interface
else:
.... # initialize some writer for the filename/path If we recommend the user to use Of course, using a runtime-checkable protocol is less error-prone in this regard. |
When type hinting, particularly in function arguments, using the more flexible abstract class
typing.IO[bytes]
is often more appropriate than the concrete typeio.Bytes
.Example
This works at runtime just fine, but type checkers will complain because
BufferedRandom
, the type offile
, is not a subtype ofio.BytesIO
. The library should have annotated the method withtyping.IO[bytes]
instead. I propose the following rule:Rule
io.BytesIO
withtyping.IO[bytes]
/typing.BinaryIO
andio.TextIO
withtyping.IO[str]
/typing.TextIO
inside function argument annotations.typing.IO[str]
andtyping.IO[bytes]
instead oftyping.TextIO
andtyping.BinaryIO
except when one of the membersbuffer
,encoding
,errors
,line_buffering
,newlines
or__enter__
is needed.References
The text was updated successfully, but these errors were encountered: