summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2003-03-06 23:54:28 (GMT)
committerRaymond Hettinger <python@rcn.com>2003-03-06 23:54:28 (GMT)
commita3e1e4cd79abe7069c8bc20db65161dd8c68b305 (patch)
tree18ff4fb0f06cc1a684da8ad62ce21a5b14c1a33c /Lib
parent2b4821347f00b01746562d58390a213924f2b102 (diff)
downloadcpython-a3e1e4cd79abe7069c8bc20db65161dd8c68b305.zip
cpython-a3e1e4cd79abe7069c8bc20db65161dd8c68b305.tar.gz
cpython-a3e1e4cd79abe7069c8bc20db65161dd8c68b305.tar.bz2
SF patch #693753: fix for bug 639806: default for dict.pop
(contributed by Michael Stone.)
Diffstat (limited to 'Lib')
-rw-r--r--Lib/UserDict.py16
-rw-r--r--Lib/test/test_types.py6
-rw-r--r--Lib/test/test_userdict.py6
3 files changed, 23 insertions, 5 deletions
diff --git a/Lib/UserDict.py b/Lib/UserDict.py
index fb9cdd5..6b5c9da 100644
--- a/Lib/UserDict.py
+++ b/Lib/UserDict.py
@@ -55,8 +55,8 @@ class UserDict:
if not self.has_key(key):
self[key] = failobj
return self[key]
- def pop(self, key):
- return self.data.pop(key)
+ def pop(self, key, *args):
+ return self.data.pop(key, *args)
def popitem(self):
return self.data.popitem()
def __contains__(self, key):
@@ -117,8 +117,16 @@ class DictMixin:
except KeyError:
self[key] = default
return default
- def pop(self, key):
- value = self[key]
+ def pop(self, key, *args):
+ if len(args) > 1:
+ raise TypeError, "pop expected at most 2 arguments, got "\
+ + repr(1 + len(args))
+ try:
+ value = self[key]
+ except KeyError:
+ if args:
+ return args[0]
+ raise
del self[key]
return value
def popitem(self):
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index d571a02..f2a7ccd 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -643,10 +643,14 @@ else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is emp
# see SF bug #689659
x = 4503599627370496L
y = 4503599627370496
-h = {x: 'anything', y: 'something else'}
+h = {x: 'anything', y: 'something else'}
if h[x] != h[y]:
raise TestFailed, "long/int key should match"
+if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
+d[k] = v
+if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
+
d[1] = 1
try:
for i in d:
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index d3e8002..cb98308 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -139,6 +139,9 @@ class UserDictTest(unittest.TestCase):
t = UserDict.UserDict(x=42)
self.assertEqual(t.pop("x"), 42)
self.assertRaises(KeyError, t.pop, "x")
+ self.assertEqual(t.pop("x", 1), 1)
+ t["x"] = 42
+ self.assertEqual(t.pop("x", 1), 42)
# Test popitem
t = UserDict.UserDict(x=42)
@@ -242,6 +245,9 @@ class UserDictMixinTest(unittest.TestCase):
self.assertEqual(s.pop(10), 'ten')
self.assert_(10 not in s)
s[10] = 'ten'
+ self.assertEqual(s.pop("x", 1), 1)
+ s["x"] = 42
+ self.assertEqual(s.pop("x", 1), 42)
# popitem
k, v = s.popitem()