]> granicus.if.org Git - python/commitdiff
Implement dict() style constructor.
authorRaymond Hettinger <python@rcn.com>
Fri, 22 Nov 2002 00:07:40 +0000 (00:07 +0000)
committerRaymond Hettinger <python@rcn.com>
Fri, 22 Nov 2002 00:07:40 +0000 (00:07 +0000)
Already supported dict() and dict(mapping).
Now supports dict(itemsequence) and
Just van Rossum's new syntax for dict(keywordargs).

Also, added related unittests.

The docs already promise dict-like behavior
so no update is needed there.

Lib/UserDict.py
Lib/test/test_userdict.py

index 96f049dd94224f109c2c2b91239e7fdf3ba3f38e..02ddfc4ff57b5ab8f4d565240c05b64ef5542b8c 100644 (file)
@@ -1,9 +1,14 @@
 """A more or less complete user-defined wrapper around dictionary objects."""
 
 class UserDict:
-    def __init__(self, dict=None):
-        self.data = {}
-        if dict is not None: self.update(dict)
+    def __init__(self, dict=None, **kwargs):
+        self.data = kwargs              # defaults to {}
+        if dict is not None:
+            if hasattr(dict,'keys'):    # handle mapping (possibly a UserDict)
+                self.update(dict)
+            else:                       # handle sequence
+                DICT = type({})  # because builtin dict is locally overridden
+                self.data.update(DICT(dict))
     def __repr__(self): return repr(self.data)
     def __cmp__(self, dict):
         if isinstance(dict, UserDict):
index a59419d4f91ba0795953bf679380882936b07169..b561ac13a3116689c0b9f31c5950dbf6945d77d3 100644 (file)
@@ -19,6 +19,9 @@ uu0 = UserDict(u0)
 uu1 = UserDict(u1)
 uu2 = UserDict(u2)
 
+verify(UserDict(one=1, two=2) == d2)            # keyword arg constructor
+verify(UserDict([('one',1), ('two',2)]) == d2)  # item sequence constructor
+
 # Test __repr__
 
 verify(str(u0) == str(d0))