[pypy-commit] pypy default: apparently kwargs.setdefault is a thing people use (e.g. the pylib)

cfbolz noreply at buildbot.pypy.org
Wed Mar 20 17:48:23 CET 2013


Author: Carl Friedrich Bolz <cfbolz at gmx.de>
Branch: 
Changeset: r62550:80dedbfdeecb
Date: 2013-03-20 17:40 +0100
http://bitbucket.org/pypy/pypy/changeset/80dedbfdeecb/

Log:	apparently kwargs.setdefault is a thing people use (e.g. the pylib)

diff --git a/pypy/objspace/std/kwargsdict.py b/pypy/objspace/std/kwargsdict.py
--- a/pypy/objspace/std/kwargsdict.py
+++ b/pypy/objspace/std/kwargsdict.py
@@ -72,9 +72,17 @@
                 values_w.append(w_value)
 
     def setdefault(self, w_dict, w_key, w_default):
-        # XXX could do better, but is it worth it?
-        self.switch_to_object_strategy(w_dict)
-        return w_dict.setdefault(w_key, w_default)
+        space = self.space
+        if self.is_correct_type(w_key):
+            key = self.unwrap(w_key)
+            w_result = self.getitem_str(w_dict, key)
+            if w_result is not None:
+                return w_result
+            self.setitem_str(w_dict, key, w_default)
+            return w_default
+        else:
+            self.switch_to_object_strategy(w_dict)
+            return w_dict.setdefault(w_key, w_default)
 
     def delitem(self, w_dict, w_key):
         # XXX could do better, but is it worth it?
diff --git a/pypy/objspace/std/test/test_kwargsdict.py b/pypy/objspace/std/test/test_kwargsdict.py
--- a/pypy/objspace/std/test/test_kwargsdict.py
+++ b/pypy/objspace/std/test/test_kwargsdict.py
@@ -146,3 +146,16 @@
 
         assert dict.fromkeys(f(a=2, b=3)) == {"a": None, "b": None}
         assert sorted(f(a=2, b=3).itervalues()) == [2, 3]
+
+    def test_setdefault(self):
+        def f(**args):
+            return args
+        d = f(a=1, b=2)
+        a = d.setdefault("a", 0)
+        assert a == 1
+        a = d.setdefault("b", 0)
+        assert a == 2
+        a = d.setdefault("c", 3)
+        assert a == 3
+        assert "KwargsDictStrategy" in self.get_strategy(d)
+


More information about the pypy-commit mailing list