You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
  5. # All Rights Reserved
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published
  9. # by the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. '''
  22. Define a struct class which behaves like a dict, but allows using
  23. object.attr alongside object['attr'].
  24. '''
  25. __all__ = ['struct']
  26. class struct(dict):
  27. '''
  28. Ease working with dicts. Allow dict.key alongside dict['key']
  29. '''
  30. def __setattr__(self, item, value):
  31. self.__setitem__(item, value)
  32. def __getattr__(self, item):
  33. return self.__getitem__(item)
  34. def show(self, indent=0, align=False, ralign=False):
  35. '''
  36. PrettyPrint method. Aligns keys right (ralign) or left (align).
  37. '''
  38. if align or ralign:
  39. width = 0
  40. for key in self.iterkeys():
  41. width = max(width, len(key))
  42. alignment = ''
  43. if not ralign:
  44. alignment = '-'
  45. fmt = '%*.*s%%%s%d.%ds: %%s' % (
  46. indent, indent, '', alignment, width, width
  47. )
  48. else:
  49. fmt = '%*.*s%%s: %%s' % (indent, indent, '')
  50. for item in self.iteritems():
  51. print(fmt % item)