kopia lustrzana https://github.com/micropython/micropython-lib
34 wiersze
935 B
Python
34 wiersze
935 B
Python
class defaultdict:
|
|
|
|
@staticmethod
|
|
def __new__(cls, default_factory=None, **kwargs):
|
|
# Some code (e.g. urllib.urlparse) expects that basic defaultdict
|
|
# functionality will be available to subclasses without them
|
|
# calling __init__().
|
|
self = super(defaultdict, cls).__new__(cls)
|
|
self.d = {}
|
|
return self
|
|
|
|
def __init__(self, default_factory=None, **kwargs):
|
|
self.d = kwargs
|
|
self.default_factory = default_factory
|
|
|
|
def __getitem__(self, key):
|
|
try:
|
|
return self.d[key]
|
|
except KeyError:
|
|
v = self.__missing__(key)
|
|
self.d[key] = v
|
|
return v
|
|
|
|
def __setitem__(self, key, v):
|
|
self.d[key] = v
|
|
|
|
def __delitem__(self, key):
|
|
del self.d[key]
|
|
|
|
def __missing__(self, key):
|
|
if self.default_factory is None:
|
|
raise KeyError(key)
|
|
return self.default_factory()
|