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

bpo-40273: Reversible mappingproxy #19513

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,7 @@ def test_methods(self):
'__iter__',
'__len__',
'__or__',
'__reversed__',
'__ror__',
'copy',
'get',
Expand Down Expand Up @@ -768,6 +769,13 @@ def test_iterators(self):
self.assertEqual(set(view.values()), set(values))
self.assertEqual(set(view.items()), set(items))

def test_reversed(self):
d = {'a': 1, 'b': 2, 'foo': 0, 'c': 3, 'd': 4}
del d['foo']
r = reversed(self.mappingproxy(d))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think creating the proxy before deleting the element makes sure that this is indeed an updating view:

Suggested change
del d['foo']
r = reversed(self.mappingproxy(d))
mp = self.mappingproxy(d)
del d['foo']
r = reversed(mp)

self.assertEqual(list(r), list('dcba'))
self.assertRaises(StopIteration, next, r)

def test_copy(self):
original = {'key1': 27, 'key2': 51, 'key3': 93}
view = self.mappingproxy(original)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`types.MappingProxyType` is now reversible.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a versionchanged entry in the main docs as well.

9 changes: 9 additions & 0 deletions Objects/descrobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,13 @@ mappingproxy_copy(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored))
return _PyObject_CallMethodIdNoArgs(pp->mapping, &PyId_copy);
}

static PyObject *
mappingproxy_reversed(mappingproxyobject *pp, PyObject *Py_UNUSED(ignored))
{
_Py_IDENTIFIER(__reversed__);
return _PyObject_CallMethodIdNoArgs(pp->mapping, &PyId___reversed__);
}

/* WARNING: mappingproxy methods must not give access
to the underlying mapping */

Expand All @@ -1094,6 +1101,8 @@ static PyMethodDef mappingproxy_methods[] = {
PyDoc_STR("D.copy() -> a shallow copy of D")},
{"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
PyDoc_STR("See PEP 585")},
{"__reversed__", (PyCFunction)mappingproxy_reversed, METH_NOARGS,
PyDoc_STR("D.__reversed__() -> reverse iterator")},
{0}
};

Expand Down