Commits

Gora Khargosh committed 6d0d6e7

Adds AttributeDict

* This class allows you to access dictionary keys
as attributes.

Signed-off-by: Gora Khargosh <gora.khargosh@gmail.com>

  • Participants
  • Parent commits d49cd49

Comments (0)

Files changed (2)

File mom/collections.py

 Queues
 ------
 .. autoclass:: SetQueue
+.. autoclass:: AttributeDict
+.. autoclass:: adict
 
 """
 
         item = queue.Queue._get(self)
         self._set_of_items.remove(item)
         return item
+
+
+class AttributeDict(dict):
+    """
+    A dictionary with attribute-style access.
+    It maps attribute access to the real dictionary.
+
+    :author: Alice Zoë Bevan–McGregor
+    :license: MIT License.
+    """
+    def __init__(self, *args, **kw):
+        dict.__init__(self, *args, **kw)
+
+    def __repr__(self):
+        return "%s(%s)" % (self.__class__.__name__,
+                           super(AttributeDict, self).__repr__())
+
+    def __delattr__(self, name):
+        del self[name]
+
+    def __getattr__(self, name):
+        if name in self.__dict__:
+            return self.__dict__.get(name)
+        return self[name]
+
+    def __setattr__(self, name, value):
+        self[name] = value
+
+
+# Alias
+attrdict = AttributeDict

File tests/test_mom_collections.py

     from Queue import Empty as QueueEmpty
 
 from threading import Thread
-from mom.collections import SetQueue
+from mom.collections import SetQueue, AttributeDict, attrdict
+
+class Test_AttributeDict(unittest2.TestCase):
+    def test_behavior(self):
+        d = AttributeDict(something="foobar", another_thing="haha")
+        self.assertEqual(d.something, "foobar")
+        self.assertEqual(d.another_thing, "haha")
+
+        d = attrdict(something="foobar", another_thing="haha")
+        self.assertEqual(d.something, "foobar")
+        self.assertEqual(d.another_thing, "haha")
+
+    def test_KeyError_when_key_not_found(self):
+        d = AttributeDict(something="foobar", another_thing="haha")
+        a = attrdict(something="foobar", another_thing="haha")
+        def foo_wrapper(d):
+            return d.not_present
+        self.assertRaises(KeyError, foo_wrapper, d)
+        self.assertRaises(KeyError, foo_wrapper, a)
 
 
 class TestSetQueue(unittest2.TestCase):