From: W. Trevor King Date: Thu, 8 Sep 2011 15:17:03 +0000 (-0400) Subject: Add Config.select_config method and improve Config's docstring. X-Git-Tag: v0.2~26 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=f7bb72109685ddff99861a9bd4e2bd8a9e7537bb;p=h5config.git Add Config.select_config method and improve Config's docstring. --- diff --git a/h5config/config.py b/h5config/config.py index 6568760..8d83174 100644 --- a/h5config/config.py +++ b/h5config/config.py @@ -240,7 +240,12 @@ class ConfigListSetting (ConfigSetting): class Config (dict): - "A class with a list `._keys` of `Setting`\s." + """A class with a list of `Setting`\s. + + `Config` instances store their values just like dictionaries, but + the attached list of `Settings`\s allows them to intelligently + dump, save, and load those values. + """ settings = [] def __init__(self, storage=None): @@ -324,3 +329,35 @@ class Config (dict): _LOG.error('could not dump {} ({!r})'.format(name, value)) raise return '\n'.join(lines) + + def select_config(self, setting_name, attribute_value=None, + attribute_name='name'): + """Select a `Config` instance from `ConfigListSetting` values + + If your don't want to select `ConfigListSetting` items by + index, you can select them by matching another attribute. For + example: + + >>> from .test import TestConfig + >>> c = TestConfig() + >>> c['children'] = [] + >>> for name in ['Jack', 'Jill']: + ... child = TestConfig() + ... child['name'] = name + ... c['children'].append(child) + >>> child = c.select_config('children', 'Jack') + >>> child # doctest: +ELLIPSIS + + >>> child['name'] + 'Jack' + + `attribute_value` defaults to `name`, because I expect that to + be the most common case. + """ + setting_value = self[setting_name] + if not setting_value: + raise KeyError(setting_value) + for item in setting_value: + if item[attribute_name] == attribute_value: + return item + raise KeyError(item_name)