diff --git a/collections.defaultdict/collections/defaultdict.py b/collections.defaultdict/collections/defaultdict.py new file mode 100644 index 00000000..3cfb7472 --- /dev/null +++ b/collections.defaultdict/collections/defaultdict.py @@ -0,0 +1,24 @@ +class defaultdict: + + 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: + if self.default_factory is None: + raise + 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): + return self.default_factory() diff --git a/collections.defaultdict/setup.py b/collections.defaultdict/setup.py new file mode 100644 index 00000000..30f227eb --- /dev/null +++ b/collections.defaultdict/setup.py @@ -0,0 +1,10 @@ +from distutils.core import setup + +setup(name='micropython-collections.defaultdict', + version='0.1', + description='collections.defaultdict module for MicroPython', + url='https://github.com/micropython/micropython/issues/405', + author='Paul Sokolovsky', + author_email='micro-python@googlegroups.com', + license='MIT', + packages=['collections']) diff --git a/collections.defaultdict/test_defaultdict.py b/collections.defaultdict/test_defaultdict.py new file mode 100644 index 00000000..167be733 --- /dev/null +++ b/collections.defaultdict/test_defaultdict.py @@ -0,0 +1,8 @@ +from collections import defaultdict + +d = defaultdict(lambda:42) +assert d[1] == 42 +d[2] = 3 +assert d[2] == 3 +del d[1] +assert d[1] == 42