weekdays.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import six
  2. from ..utils import str_coercible
  3. from .weekday import WeekDay
  4. @str_coercible
  5. class WeekDays(object):
  6. def __init__(self, bit_string_or_week_days):
  7. if isinstance(bit_string_or_week_days, six.string_types):
  8. self._days = set()
  9. if len(bit_string_or_week_days) != WeekDay.NUM_WEEK_DAYS:
  10. raise ValueError(
  11. 'Bit string must be {0} characters long.'.format(
  12. WeekDay.NUM_WEEK_DAYS
  13. )
  14. )
  15. for index, bit in enumerate(bit_string_or_week_days):
  16. if bit not in '01':
  17. raise ValueError(
  18. 'Bit string may only contain zeroes and ones.'
  19. )
  20. if bit == '1':
  21. self._days.add(WeekDay(index))
  22. elif isinstance(bit_string_or_week_days, WeekDays):
  23. self._days = bit_string_or_week_days._days
  24. else:
  25. self._days = set(bit_string_or_week_days)
  26. def __eq__(self, other):
  27. if isinstance(other, WeekDays):
  28. return self._days == other._days
  29. elif isinstance(other, six.string_types):
  30. return self.as_bit_string() == other
  31. else:
  32. return NotImplemented
  33. def __iter__(self):
  34. for day in sorted(self._days):
  35. yield day
  36. def __contains__(self, value):
  37. return value in self._days
  38. def __repr__(self):
  39. return '%s(%r)' % (
  40. self.__class__.__name__,
  41. self.as_bit_string()
  42. )
  43. def __unicode__(self):
  44. return u', '.join(six.text_type(day) for day in self)
  45. def as_bit_string(self):
  46. return ''.join(
  47. '1' if WeekDay(index) in self._days else '0'
  48. for index in six.moves.xrange(WeekDay.NUM_WEEK_DAYS)
  49. )