Skip to content

Subtype for memoryview required to pass mypy checks but triggersTypeError in Python #18053

Closed
@lgautier

Description

@lgautier

Bug Report

Specifying a subtype for memoryview is required to pass mypy checks, but this create a TypeError in Python.

To Reproduce

This fails mypy checks:

import typing

def foo(m: memoryview) -> memoryview:
    return m

def bar(n: int, t: typing.Literal['i', 'd']) -> memoryview:
    return memoryview(bytes(n)).cast(t)

res = foo(bar(8, 'i'))
$ mypy test-type-hints.py 
test-type-hints.py:7: error: Incompatible return value type (got "memoryview[int] | memoryview[float]", expected "memoryview[int]")  [return-value]
Found 1 error in 1 file (checked 1 source file)
$ python test-type-hints.py 

Fixing mypy checks triggers Python error:

import typing

def foo(m: memoryview[int]) -> memoryview[int]:
    return m

@typing.overload
def bar(n: int, t: typing.Literal['i']) -> memoryview[int]: ...

@typing.overload
def bar(n: int, t: typing.Literal['d']) -> memoryview[float]: ...

    
def bar(n: int, t: typing.Literal['i', 'd']) -> memoryview[int] | memoryview[float]:
    return memoryview(bytes(n)).cast(t)

res = foo(bar(8, 'i'))
$ mypy test-type-hints.py 
Success: no issues found in 1 source file
$ python test-type-hints.py 
Traceback (most recent call last):
  File "/some/path/test-type-hints.py", line 3, in <module>
    def foo(m: memoryview[int]) -> memoryview[int]:
               ~~~~~~~~~~^^^^^
TypeError: type 'memoryview' is not subscriptable

Expected Behavior

$ mypy test-type-hints.py
Success: no issues found in 1 source file
$ python test-type-hints.py 

Actual Behavior

Either mypy fails but Python can run the code, or mypy passes but Python doesn't run.

Your Environment

$ mypy --version
mypy 1.13.0 (compiled: yes)
$ python --version
Python 3.12.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions