From: W. Trevor King Date: Sun, 25 Sep 2011 23:15:07 +0000 (-0400) Subject: Change attribute_name argument to the more flexible get_attribute in Config.select_co... X-Git-Tag: v0.2~21 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=3e8e8a12abe51c5ee882cf4e594d3555588a8fd4;p=h5config.git Change attribute_name argument to the more flexible get_attribute in Config.select_config. --- diff --git a/h5config/config.py b/h5config/config.py index bbe9469..0dd6898 100644 --- a/h5config/config.py +++ b/h5config/config.py @@ -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 + + >>> 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)