Last active
August 29, 2015 13:55
-
-
Save tychoish/8773038 to your computer and use it in GitHub Desktop.
Python State Object Classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| def collect_arguments(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--version') | |
| args = ConfigArgs() | |
| return parser.parse_args(namespace=args) | |
| def set_defaults(fn, obj): | |
| if os.path.exists(fn): | |
| logger.debug("adding values from configuration file".format(fn)) | |
| conf = Configuration(fn) | |
| for k in conf: | |
| logger.debug('set default of {0} to {1}'.format(k, conf[k])) | |
| setattr(obj, k, conf[k]) | |
| return obj | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AttributeDict(dict): | |
| def __init__(self, value=None): | |
| if value is None: | |
| pass | |
| elif isinstance(value, dict): | |
| for key in value: | |
| self.__setitem__(key, value[key]) | |
| else: | |
| raise TypeError('expected dict') | |
| def __setitem__(self, key, value): | |
| if '-' in key: | |
| key = key.replace('-', '_') | |
| if isinstance(value, dict) and not isinstance(value, AttributeDict): | |
| value = AttributeDict(value) | |
| dict.__setitem__(self, key, value) | |
| def __getitem__(self, key): | |
| if '-' in key: | |
| key = key.replace('-', '_') | |
| NotFound = object() | |
| found = self.get(key, NotFound) | |
| if found is NotFound: | |
| err = 'key named "{0}" does not exist.'.format(key) | |
| raise AttributeError(err) | |
| else: | |
| return found | |
| def __contains__(self, key): | |
| if '-' in key: | |
| key = key.replace('-', '_') | |
| try: | |
| return self.has_key(key) | |
| except AttributeError: | |
| return key in self.keys() | |
| __setattr__ = __setitem__ | |
| __getattr__ = __getitem__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ConfigArgs(ConfigBase): | |
| def __init__(self): | |
| self.__construct('_depends', '_has') | |
| self._version = [ None ] | |
| @property | |
| def version(self): | |
| return self._version | |
| @version.setter | |
| def version(self, value): | |
| if ',' in value: | |
| self._version = value.split(',') | |
| else: | |
| self._version = [ value ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ConfigBase(object): | |
| __is_frozen = False | |
| def __construct(self, *keys): | |
| for k in keys: | |
| setattr(self, key, None) | |
| def __setattr__(self, key, value): | |
| if __is_frozen is True: | |
| pass | |
| else: | |
| object.__setattr(self, key, value) | |
| def freeze(self): | |
| self.__is_frozen = True | |
| @property | |
| def dict(self): | |
| return { k: getattr(self, k) | |
| for k in ( a | |
| for a in dir(self) | |
| if a != 'dict' and not a.startswith('_') ) | |
| } | |
| @dict.setter | |
| def dict(self): | |
| raise TypeError("the dict attribute is not settable in Arguments() objects") | |
| def __repr__(self): | |
| return str(self.dict) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import yaml | |
| import json | |
| class Configuration(AttributeDict): | |
| def __init__(self, filename, directory=None): | |
| if directory is None: | |
| directory = os.path.split(os.path.abspath(filename))[0] | |
| file_path = os.path.join(directory, filename) | |
| if filename.endswith('yaml'): | |
| with open(file_path, 'r') as f: | |
| conf = [d for d in yaml.load(f)][0] | |
| elif filename.endswith('json'): | |
| with open(file_Path, 'r') as f: | |
| conf = [d fpr d in json.load(f)][0] | |
| for key, value in conf.items(): | |
| if isinstance(value, (list, tuple)): | |
| for item in value: | |
| if isinstance(item, dict): | |
| setattr(self, key, AttributeDict(item)) | |
| else: | |
| setattr(self, key, value) | |
| else: | |
| if isinstance(value, dict): | |
| setattr(self, key, AttributeDict(value)) | |
| else: | |
| setattr(self, key, value) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment