From e8b001f46f7d5dff9268cf5a800a35bb505112bf Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sun, 3 Jan 2010 06:56:10 +0000 Subject: [PATCH] [1.1.X] Fixed #12476 -- Forced the rollout of generators passed to SortedDict so that the data source can be read twice. Thanks to gsf for the report, and Alex for the patch. Backport of r12064 from trunk. git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.1.X@12065 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/utils/datastructures.py | 7 +++++++ tests/regressiontests/datastructures/tests.py | 7 +++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index 06cf6c6b75..adcc3546d0 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -1,3 +1,5 @@ +from types import GeneratorType + from django.utils.copycompat import deepcopy @@ -65,6 +67,11 @@ class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} + elif isinstance(data, GeneratorType): + # Unfortunately we need to be able to read a generator twice. Once + # to get the data into self with our super().__init__ call and a + # second time to setup keyOrder correctly + data = list(data) super(SortedDict, self).__init__(data) if isinstance(data, dict): self.keyOrder = data.keys() diff --git a/tests/regressiontests/datastructures/tests.py b/tests/regressiontests/datastructures/tests.py index e658f3302e..b7885e65a4 100644 --- a/tests/regressiontests/datastructures/tests.py +++ b/tests/regressiontests/datastructures/tests.py @@ -60,9 +60,9 @@ MultiValueDictKeyError: "Key 'lastname' not found in >> d.setlist('lastname', ['Holovaty', 'Willison']) >>> d.getlist('lastname') ['Holovaty', 'Willison'] ->>> d.values() +>>> d.values() ['Developer', 'Simon', 'Willison'] ->>> list(d.itervalues()) +>>> list(d.itervalues()) ['Developer', 'Simon', 'Willison'] ### SortedDict ################################################################# @@ -95,6 +95,9 @@ True >>> d.pop('one', 'missing') 'missing' +>>> SortedDict((i, i) for i in xrange(3)) +{0: 0, 1: 1, 2: 2} + We don't know which item will be popped in popitem(), so we'll just check that the number of keys has decreased. >>> l = len(d)