Created
March 4, 2012 03:28
-
-
Save dcolish/1970445 to your computer and use it in GitHub Desktop.
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 Values: | |
| def __init__(self, defaults=None): | |
| if defaults: | |
| for (attr, val) in defaults.items(): | |
| setattr(self, attr, val) | |
| def __str__(self): | |
| return str(self.__dict__) | |
| __repr__ = _repr | |
| def __eq__(self, other): | |
| if isinstance(other, Values): | |
| return self.__dict__ == other.__dict__ | |
| elif isinstance(other, dict): | |
| return self.__dict__ == other | |
| else: | |
| return NotImplemented | |
| def _update_careful(self, dict): | |
| """ | |
| Update the option values from an arbitrary dictionary, but only | |
| use keys from dict that already have a corresponding attribute | |
| in self. Any keys in dict without a corresponding attribute | |
| are silently ignored. | |
| """ | |
| for attr in dir(self): | |
| if attr in dict: | |
| dval = dict[attr] | |
| if dval is not None: | |
| setattr(self, attr, dval) | |
| def _update_loose(self, dict): | |
| """ | |
| Update the option values from an arbitrary dictionary, | |
| using all keys from the dictionary regardless of whether | |
| they have a corresponding attribute in self or not. | |
| """ | |
| self.__dict__.update(dict) | |
| def _update(self, dict, mode): | |
| if mode == "careful": | |
| self._update_careful(dict) | |
| elif mode == "loose": | |
| self._update_loose(dict) | |
| else: | |
| raise ValueError("invalid update mode: %r" % mode) | |
| def read_module(self, modname, mode="careful"): | |
| __import__(modname) | |
| mod = sys.modules[modname] | |
| self._update(vars(mod), mode) | |
| def read_file(self, filename, mode="careful"): | |
| vars = {} | |
| exec(open(filename).read(), vars) | |
| self._update(vars, mode) | |
| def ensure_value(self, attr, value): | |
| if not hasattr(self, attr) or getattr(self, attr) is None: | |
| setattr(self, attr, value) | |
| return getattr(self, attr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment