From a3f98d6bac3fbfc0e010360b11793bbd8a8f4c85 Mon Sep 17 00:00:00 2001 From: Tim Peters Date: Sat, 21 Apr 2001 09:13:15 +0000 Subject: [PATCH] Give UserDict new __contains__ and __iter__ methods. --- Lib/UserDict.py | 4 ++++ Lib/test/test_userdict.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Lib/UserDict.py b/Lib/UserDict.py index b642db73b57..bbd4ca04c4a 100644 --- a/Lib/UserDict.py +++ b/Lib/UserDict.py @@ -40,3 +40,7 @@ class UserDict: return self.data[key] def popitem(self): return self.data.popitem() + def __contains__(self, key): + return key in self.data + def __iter__(self): + return iter(self.data) diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index 08b7a13e4a0..9aa01d0de77 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -81,12 +81,15 @@ verify(u2.keys() == d2.keys()) verify(u2.items() == d2.items()) verify(u2.values() == d2.values()) -# Test has_key +# Test has_key and "in". for i in u2.keys(): verify(u2.has_key(i) == 1) + verify((i in u2) == 1) verify(u1.has_key(i) == d1.has_key(i)) + verify((i in u1) == (i in d1)) verify(u0.has_key(i) == d0.has_key(i)) + verify((i in u0) == (i in d0)) # Test update @@ -100,3 +103,14 @@ for i in u2.keys(): verify(u2.get(i) == u2[i]) verify(u1.get(i) == d1.get(i)) verify(u0.get(i) == d0.get(i)) + +# Test "in" iteration. +for i in xrange(20): + u2[i] = str(i) +ikeys = [] +for k in u2: + ikeys.append(k) +ikeys.sort() +keys = u2.keys() +keys.sort() +verify(ikeys == keys)