weekdays.py 1.7 KB

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