Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e4827eb

Browse files
committed
Bring UserDict in-sync with changes to dict.
Constructor accepts optional keyword arguments after a optional items list. Add fromkeys() as an alternate constructor from an iterable over keys. Expand related unittests.
1 parent e33d3df commit e4827eb

2 files changed

Lines changed: 25 additions & 6 deletions

File tree

Lib/UserDict.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
class UserDict:
44
def __init__(self, dict=None, **kwargs):
5-
self.data = kwargs # defaults to {}
5+
self.data = {}
66
if dict is not None:
7-
if hasattr(dict,'keys'): # handle mapping (possibly a UserDict)
8-
self.update(dict)
9-
else: # handle sequence
10-
DICT = type({}) # because builtin dict is locally overridden
11-
self.data.update(DICT(dict))
7+
if not hasattr(dict,'keys'):
8+
dict = type({})(dict) # make mapping from a sequence
9+
self.update(dict)
10+
if len(kwargs):
11+
self.update(kwargs)
1212
def __repr__(self): return repr(self.data)
1313
def __cmp__(self, dict):
1414
if isinstance(dict, UserDict):
@@ -61,6 +61,12 @@ def popitem(self):
6161
return self.data.popitem()
6262
def __contains__(self, key):
6363
return key in self.data
64+
def fromkeys(cls, iterable, value=None):
65+
d = cls()
66+
for key in iterable:
67+
d[key] = value
68+
return d
69+
fromkeys = classmethod(fromkeys)
6470

6571
class IterableUserDict(UserDict):
6672
def __iter__(self):

Lib/test/test_userdict.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
d0 = {}
77
d1 = {"one": 1}
88
d2 = {"one": 1, "two": 2}
9+
d3 = {"one": 1, "two": 3, "three": 5}
10+
d4 = {"one": None, "two": None}
11+
d5 = {"one": 1, "two": 1}
912

1013
# Test constructors
1114

@@ -21,6 +24,16 @@
2124

2225
verify(UserDict(one=1, two=2) == d2) # keyword arg constructor
2326
verify(UserDict([('one',1), ('two',2)]) == d2) # item sequence constructor
27+
verify(UserDict(dict=[('one',1), ('two',2)]) == d2)
28+
verify(UserDict([('one',1), ('two',2)], two=3, three=5) == d3) # both together
29+
30+
verify(UserDict.fromkeys('one two'.split()) == d4) # alternate constructor
31+
verify(UserDict().fromkeys('one two'.split()) == d4)
32+
verify(UserDict.fromkeys('one two'.split(), 1) == d5)
33+
verify(UserDict().fromkeys('one two'.split(), 1) == d5)
34+
verify(u1.fromkeys('one two'.split()) is not u1)
35+
verify(isinstance(u1.fromkeys('one two'.split()), UserDict))
36+
verify(isinstance(u2.fromkeys('one two'.split()), IterableUserDict))
2437

2538
# Test __repr__
2639

0 commit comments

Comments
 (0)