Skip to content
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

Add tuple key type for memoryview.__getitem__ and __setitem__ #11294

Closed
posthumz opened this issue Jan 20, 2024 · 1 comment · Fixed by #11296
Closed

Add tuple key type for memoryview.__getitem__ and __setitem__ #11294

posthumz opened this issue Jan 20, 2024 · 1 comment · Fixed by #11296
Labels
stubs: false positive Type checkers report false errors

Comments

@posthumz
Copy link
Contributor

posthumz commented Jan 20, 2024

memoryview should accept a length ndim tuple as the key of __getitem__ and __setitem__ according to memoryview

Maybe change

- def __getitem__(self, __key: SupportsIndex) -> int: ...
+ def __getitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...] ) -> int: ...

- def __setitem__(self, __key: SupportsIndex, __value: SupportsIndex) -> None: ...
+ def __setitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...], __value: SupportsIndex) -> None: ...

Example:

>>> class Foo:
...     def __index__(self):
...         return 0
>>> view = memoryview(bytearray(range(4)))  # [0, 1, 2, 3], ndim=1
>>> print(view[Foo(),])                     # getting with length 1 tuple
0
>>> view[Foo(),] = 4                        # setting with length 1 tuple
>>> print(view.tolist())
[4, 1, 2, 3]
>>> view = view.cast("b", (2, 2))           # [[4, 1], [2, 3]], ndim=2
>>> print(view[Foo(), 1])                   # getting with length 2 tuple
1
>>> view[Foo(), 1] = 5
>>> print(view.tolist())                    # setting with length 2 tuple
[[4, 5], [2, 3]]
@srittau srittau added the stubs: false positive Type checkers report false errors label Jan 21, 2024
@srittau
Copy link
Collaborator

srittau commented Jan 21, 2024

Makes sense to me. PR welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants