bunch.py 993 B

12345678910111213141516171819202122232425262728293031323334
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. # Taken from Paver's paver.options module.
  5. class Bunch(dict):
  6. """A dictionary that provides attribute-style access."""
  7. def __repr__(self):
  8. keys = self.keys()
  9. keys.sort()
  10. args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])
  11. return '%s(%s)' % (self.__class__.__name__, args)
  12. def __getitem__(self, key):
  13. item = dict.__getitem__(self, key)
  14. if callable(item):
  15. return item()
  16. return item
  17. def __getattr__(self, name):
  18. try:
  19. return self[name]
  20. except KeyError:
  21. raise AttributeError(name)
  22. __setattr__ = dict.__setitem__
  23. def __delattr__(self, name):
  24. try:
  25. del self[name]
  26. except KeyError:
  27. raise AttributeError(name)