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

gh-125420: implement Sequence.__contains__ API on memoryview objects #125441

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Lib/test/test_memoryview.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,24 @@ def test_iter(self):
m = self._view(b)
self.assertEqual(list(m), [m[i] for i in range(len(m))])

def test_contains(self):
for tp in self._types:
b = tp(self._source)
m = self._view(b)
for c in list(m):
with self.subTest(self._source, buffer_type=tp, item=c):
self.assertIn(c, m)

with self.subTest('empty buffer'):
empty = tp(b'')
mview = self._view(empty)
self.assertNotIn(0, mview)

with self.subTest('not found'):
b = tp(b'abc')
m = self._view(b)
self.assertNotIn(ord('d'), m)

def test_setitem_readonly(self):
if not self.ro_type:
self.skipTest("no read-only type to test")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Implement :meth:`~object.__contains__` for :class:`memoryview` objects.
Patch by Bénédikt Tran.
38 changes: 34 additions & 4 deletions Objects/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2483,6 +2483,37 @@ memory_item_multi(PyMemoryViewObject *self, PyObject *tup)
return unpack_single(self, ptr, fmt);
}

/* Test the membership of an item. */
static int
memory_contains(PyObject *self, PyObject *value)
{
PyObject *iter = PyObject_GetIter(self);
if (iter == NULL) {
return -1;
}

PyObject *item = NULL;
while (PyIter_NextItem(iter, &item)) {
if (item == NULL) {
Py_DECREF(iter);
return -1;
}
if (item == value) {
Py_DECREF(item);
Py_DECREF(iter);
return 1;
}
int contained = PyObject_RichCompareBool(item, value, Py_EQ);
Py_DECREF(item);
if (contained != 0) {
Py_DECREF(iter);
return contained;
}
}
Py_DECREF(iter);
return 0;
}

static inline int
init_slice(Py_buffer *base, PyObject *key, int dim)
{
Expand Down Expand Up @@ -2741,10 +2772,9 @@ static PyMappingMethods memory_as_mapping = {

/* As sequence */
static PySequenceMethods memory_as_sequence = {
memory_length, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
memory_item, /* sq_item */
.sq_length = memory_length,
.sq_item = memory_item,
.sq_contains = memory_contains
};


Expand Down
Loading