Change attribute_name argument to the more flexible get_attribute in Config.select_co...
authorW. Trevor King <wking@drexel.edu>
Sun, 25 Sep 2011 23:15:07 +0000 (19:15 -0400)
committerW. Trevor King <wking@drexel.edu>
Sun, 25 Sep 2011 23:15:07 +0000 (19:15 -0400)
h5config/config.py

index bbe9469ee1dc1d1dc34f49b07bd59464ec28db33..0dd6898228f1899b7b3597c4f10ff631c7532f22 100644 (file)
@@ -334,7 +334,7 @@ class Config (dict):
         return '\n'.join(lines)
 
     def select_config(self, setting_name, attribute_value=None,
-                      attribute_name='name'):
+                      get_attribute=lambda value : value['name']):
         """Select a `Config` instance from `ConfigListSetting` values
 
         If your don't want to select `ConfigListSetting` items by
@@ -354,13 +354,30 @@ class Config (dict):
         >>> child['name']
         'Jack'
 
-        `attribute_value` defaults to `name`, because I expect that to
-        be the most common case.
+        `get_attribute` defaults to returning `value['name']`, because
+        I expect that to be the most common case, but you can use
+        another function if neccessary, for example to drill down more
+        than one level.  Here we select by grandchild name:
+
+        >>> for name in ['Jack', 'Jill']:
+        ...     grandchild = TestConfig()
+        ...     grandchild['name'] = name + ' Junior'
+        ...     child = c.select_config('children', name)
+        ...     child['children'] = [grandchild]
+        >>> get_grandchild = lambda value : value['children'][0]['name']
+        >>> get_grandchild(child)
+        'Jill Junior'
+        >>> child = c.select_config('children', 'Jack Junior',
+        ...     get_attribute=get_grandchild)
+        >>> child  # doctest: +ELLIPSIS
+        <TestConfig ...>
+        >>> child['name']
+        'Jack'
         """
-        setting_value = self[setting_name]
+        setting_value = self.get(setting_name, None)
         if not setting_value:
-            raise KeyError(setting_value)
+            raise KeyError(setting_name)
         for item in setting_value:
-            if item[attribute_name] == attribute_value:
+            if get_attribute(item) == attribute_value:
                 return item
         raise KeyError(attribute_value)