From 59d127e45f5ed31e346162a0ac312f672c096821 Mon Sep 17 00:00:00 2001 From: Anton Baklanov Date: Wed, 17 Apr 2013 18:20:31 +0300 Subject: [PATCH] Fixed #20276 -- Implemented __bool__ for MergeDict MergeDict evaluates now to False if all contained dicts are empty. Thanks til for the report and the initial patch. --- django/utils/datastructures.py | 6 ++++++ tests/utils_tests/test_datastructures.py | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index 64c218fe43..b3060202be 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -14,6 +14,12 @@ class MergeDict(object): def __init__(self, *dicts): self.dicts = dicts + def __bool__(self): + return any(self.dicts) + + def __nonzero__(self): + return type(self).__bool__(self) + def __getitem__(self, key): for dict_ in self.dicts: try: diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index 3161c04f97..91111cc2ed 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -203,6 +203,13 @@ class MergeDictTests(SimpleTestCase): ('key2', ['value2', 'value3']), ('key4', ['value5', 'value6'])]) + def test_bool_casting(self): + empty = MergeDict({}, {}, {}) + not_empty = MergeDict({}, {}, {"key": "value"}) + self.assertFalse(empty) + self.assertTrue(not_empty) + + class MultiValueDictTests(SimpleTestCase): def test_multivaluedict(self):