From ac2ae5831e48b1d2516832b6eb07b2780b0aa0a4 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 14 Apr 2014 21:20:31 +0300 Subject: [PATCH] collections.defaultdict: Add implementation. In a namespace package. --- .../collections/defaultdict.py | 24 +++++++++++++++++++ collections.defaultdict/setup.py | 10 ++++++++ collections.defaultdict/test_defaultdict.py | 8 +++++++ 3 files changed, 42 insertions(+) create mode 100644 collections.defaultdict/collections/defaultdict.py create mode 100644 collections.defaultdict/setup.py create mode 100644 collections.defaultdict/test_defaultdict.py 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