modify config.InstanceContext to raise an AttributeError for __setitem__ on non-pre-existing attributes - this makes a lot of sense :)
authorTero Marttila <terom@fixme.fi>
Wed, 17 Jun 2009 18:11:38 +0300
changeset 134 ea05fe81ff67
parent 133 0c1c092bbc5d
child 135 6534c77de93f
modify config.InstanceContext to raise an AttributeError for __setitem__ on non-pre-existing attributes - this makes a lot of sense :)
degal/config.py
--- a/degal/config.py	Wed Jun 17 18:08:49 2009 +0300
+++ b/degal/config.py	Wed Jun 17 18:11:38 2009 +0300
@@ -8,12 +8,25 @@
     """
         An object that behaves like a dict, performing all item lookups as attribute lookups on the given object.
 
+        Additionally, it only lets you re-bind existing attributes via setitem, raising AttributeError if setting
+        unknown attributes.
+
         Useful for binding an exec statement's locals.
     """
 
     def __init__ (self, obj) : self.obj = obj
     def __getitem__ (self, key) : return getattr(self.obj, key)
-    def __setitem__ (self, key, value) : setattr(self.obj, key, value)
+    def __setitem__ (self, key, value) : 
+        """
+            Replace the named attribute, asserting that the target has such an attribute.
+        """
+        
+        # test
+        if hasattr(self.obj, key) :
+            setattr(self.obj, key, value)
+        
+        else :
+            raise AttributeError(key)
 
 class ConfigurationMachinery (object) :
     """