typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

memoryview.cast("c") false error

Open jdufresne opened this issue 3 years ago • 5 comments

Given the following code snippet:

buf = b"abcdefg"
view = memoryview(buf).cast("c")
for c in view:
    print(type(c))
    if c == b"c":
        print("Found c")

Inside the loop, the variable c is always type bytes. However, mypy believes it to be int and reports an error:

$ mypy --version
mypy 0.961 (compiled: yes)
$ mypy --strict ~/test.py
/home/jon/test.py:5: error: Non-overlapping equality check (left operand type: "int", right operand type: "Literal[b'c']")
Found 1 error in 1 file (checked 1 source file)

Running the script confirms the type is bytes:

$ python ~/test.py
<class 'bytes'>
<class 'bytes'>
<class 'bytes'>
Found c
<class 'bytes'>
<class 'bytes'>
<class 'bytes'>
<class 'bytes'>

Docs on this method: https://docs.python.org/3/library/stdtypes.html#memoryview.cast

jdufresne avatar Jun 26 '22 16:06 jdufresne

It looks to me that memoryview should be generic over the format. That said, I'm uncomfortable making a change like this as long as we don't have type var defaults. (python/typing#307)

srittau avatar Jun 26 '22 17:06 srittau

It looks to me that memoryview should be generic over the format.

Yeah, this might be quite a big breaking change given that it's a builtin.

AlexWaygood avatar Jun 26 '22 17:06 AlexWaygood

@jdufresne Off-topic, but I skimmed the chardet PR you linked. The one nice thing the typeshed stubs for chardet do is distinguish between cases when ResultDict fields can be None or not. Might be worth seeing if there's something worth stealing from there (make sure to check latest typeshed stubs since there were some recent changes)

hauntsaninja avatar Jul 08 '22 07:07 hauntsaninja

Marking as deferred unless/until PEP 696 is accepted by the Steering Council and implemented by type checkers.

AlexWaygood avatar Nov 01 '23 18:11 AlexWaygood

See #11422 for the type var generics feature tracker.

srittau avatar Feb 14 '24 14:02 srittau