From c3fabb282d429de931ef10c91cee55700578eb86 Mon Sep 17 00:00:00 2001 From: Mitar Date: Mon, 15 Oct 2012 04:16:46 -0700 Subject: [PATCH 1/2] Allow reversed iteration over SortedDict. Iterators cannot be reversed easily without this method. --- django/utils/datastructures.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index ad17573104..d94a05dfb4 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -160,6 +160,9 @@ class SortedDict(dict): def __iter__(self): return iter(self.keyOrder) + def __reversed__(self): + return reversed(self.keyOrder) + def pop(self, k, *args): result = super(SortedDict, self).pop(k, *args) try: From 2811e543c648a0669c88185a4d117eeb8ff09689 Mon Sep 17 00:00:00 2001 From: Mitar Date: Mon, 15 Oct 2012 12:12:10 -0700 Subject: [PATCH 2/2] Added tests for reversed iteration over SortedDict. --- tests/regressiontests/utils/datastructures.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/regressiontests/utils/datastructures.py b/tests/regressiontests/utils/datastructures.py index dbc65d37a8..7c81ccd172 100644 --- a/tests/regressiontests/utils/datastructures.py +++ b/tests/regressiontests/utils/datastructures.py @@ -128,6 +128,12 @@ class SortedDictTests(SimpleTestCase): self.assertEqual(self.d1, {}) self.assertEqual(self.d1.keyOrder, []) + def test_reversed(self): + self.assertEqual(list(self.d1), [7, 1, 9]) + self.assertEqual(list(self.d2), [1, 9, 0, 7]) + self.assertEqual(list(reversed(self.d1)), [9, 1, 7]) + self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1]) + def test_insert(self): d = SortedDict() with warnings.catch_warnings(record=True) as w: