diff options
author | Raymond Hettinger <python@rcn.com> | 2002-11-22 00:07:40 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2002-11-22 00:07:40 (GMT) |
commit | 54405456e5c2b76879472051c23e6c1c9f433beb (patch) | |
tree | ab0827e9b4532d0ad144d9e0033d451410eb41a3 /Lib | |
parent | ba2cf078d2bd8705f61afda7081522981674882e (diff) | |
download | cpython-54405456e5c2b76879472051c23e6c1c9f433beb.zip cpython-54405456e5c2b76879472051c23e6c1c9f433beb.tar.gz cpython-54405456e5c2b76879472051c23e6c1c9f433beb.tar.bz2 |
Implement dict() style constructor.
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.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/UserDict.py | 11 | ||||
-rw-r--r-- | Lib/test/test_userdict.py | 3 |
2 files changed, 11 insertions, 3 deletions
diff --git a/Lib/UserDict.py b/Lib/UserDict.py index 96f049d..02ddfc4 100644 --- a/Lib/UserDict.py +++ b/Lib/UserDict.py @@ -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): diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index a59419d..b561ac1 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -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)) |