classUserDict(MutableMapping):# Start by filling-out the abstract methodsdef__init__(*args, **kwargs):ifnot args:
raise TypeError("descriptor '__init__' of 'UserDict' object ""needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
if args:
dict = args[0]
elif'dict'in kwargs:
dict = kwargs.pop('dict')
import warnings
warnings.warn("Passing 'dict' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
else:
dict = None
self.data = {}
if dict isnotNone:
self.update(dict)
if len(kwargs):
self.update(kwargs)
def__len__(self):return len(self.data)
def__getitem__(self, key):if key in self.data:
return self.data[key]
if hasattr(self.__class__, "__missing__"):
return self.__class__.__missing__(self, key)
raise KeyError(key)
def__setitem__(self, key, item): self.data[key] = item
def__delitem__(self, key):del self.data[key]
def__iter__(self):return iter(self.data)
# Modify __contains__ to work correctly when __missing__ is presentdef__contains__(self, key):return key in self.data
# Now, add the methods in dicts but not in MutableMappingdef__repr__(self):return repr(self.data)
defcopy(self):if self.__class__ is UserDict:
return UserDict(self.data.copy())
import copy
data = self.data
try:
self.data = {}
c = copy.copy(self)
finally:
self.data = data
c.update(self)
return c
@classmethoddeffromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d