-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Surprising error involving bytes duck-type compatibility #12643
Comments
Unfortunately I believe this may actually be expected behaviour, despite the fact that it is somewhat baffling and counter-intuitive. It likely stems from the documentation for
In other words (although it is not stated in a PEP anywhere), the from typing import Union
Buffer = Union[bytes, bytearray, memoryview]
def f(data: Buffer) -> str:
if not isinstance(data, bytes):
data = bytes(data) # error: Statement is unreachable
return data.decode() # error: Item "memoryview" of "Union[bytes, bytearray, memoryview]" has no attribute "decode We can also see that mypy is able to quite happily do type narrowing using from typing import Union
Buffer = Union[bytes, int, list[int]]
def f(data: Buffer) -> str:
if not isinstance(data, bytes):
data = bytes(data)
return data.decode() |
Was just going to write the same thing @AlexWaygood said :) We maybe should reconsider this ByteString behavior. It's confusing, underspecified, and not useful as frequently as with int/float. |
Agree 100%. |
not
conditions
You are going to send lady Liskov to an early grave 😄 This looks like a bug to me: how can I believe I have been fighting mypy issues for two years in psycopg 3 codebase thanks to this helpful shortcut. |
The problem with duck typing is even worse: #12824 |
|
|
FWIW the original example doesn't give an error in the current master (and probably also in 0.990) |
Mypy seems to fail to narrow down union with
not
conditions. I couldn't find an issue already open on the topic.To Reproduce
Running mypy on the following sample, an error is reported:
This is unexpected because, after the
if
, the type ofdata
is definitelybytes
.If a test
if isinstance(data, (bytearray, memoryview))
is used instead there is no error. However this has likely a lower performance and requires more maintenance should other types be added to the union.Your Environment
pyproject.toml
:The text was updated successfully, but these errors were encountered: