_looper.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """
  2. Helper for looping over sequences, particular in templates.
  3. Often in a loop in a template it's handy to know what's next up,
  4. previously up, if this is the first or last item in the sequence, etc.
  5. These can be awkward to manage in a normal Python loop, but using the
  6. looper you can get a better sense of the context. Use like::
  7. >>> for loop, item in looper(['a', 'b', 'c']):
  8. ... print loop.number, item
  9. ... if not loop.last:
  10. ... print '---'
  11. 1 a
  12. ---
  13. 2 b
  14. ---
  15. 3 c
  16. """
  17. import sys
  18. from Cython.Tempita.compat3 import basestring_
  19. __all__ = ['looper']
  20. class looper(object):
  21. """
  22. Helper for looping (particularly in templates)
  23. Use this like::
  24. for loop, item in looper(seq):
  25. if loop.first:
  26. ...
  27. """
  28. def __init__(self, seq):
  29. self.seq = seq
  30. def __iter__(self):
  31. return looper_iter(self.seq)
  32. def __repr__(self):
  33. return '<%s for %r>' % (
  34. self.__class__.__name__, self.seq)
  35. class looper_iter(object):
  36. def __init__(self, seq):
  37. self.seq = list(seq)
  38. self.pos = 0
  39. def __iter__(self):
  40. return self
  41. def __next__(self):
  42. if self.pos >= len(self.seq):
  43. raise StopIteration
  44. result = loop_pos(self.seq, self.pos), self.seq[self.pos]
  45. self.pos += 1
  46. return result
  47. if sys.version < "3":
  48. next = __next__
  49. class loop_pos(object):
  50. def __init__(self, seq, pos):
  51. self.seq = seq
  52. self.pos = pos
  53. def __repr__(self):
  54. return '<loop pos=%r at %r>' % (
  55. self.seq[self.pos], self.pos)
  56. def index(self):
  57. return self.pos
  58. index = property(index)
  59. def number(self):
  60. return self.pos + 1
  61. number = property(number)
  62. def item(self):
  63. return self.seq[self.pos]
  64. item = property(item)
  65. def __next__(self):
  66. try:
  67. return self.seq[self.pos + 1]
  68. except IndexError:
  69. return None
  70. __next__ = property(__next__)
  71. if sys.version < "3":
  72. next = __next__
  73. def previous(self):
  74. if self.pos == 0:
  75. return None
  76. return self.seq[self.pos - 1]
  77. previous = property(previous)
  78. def odd(self):
  79. return not self.pos % 2
  80. odd = property(odd)
  81. def even(self):
  82. return self.pos % 2
  83. even = property(even)
  84. def first(self):
  85. return self.pos == 0
  86. first = property(first)
  87. def last(self):
  88. return self.pos == len(self.seq) - 1
  89. last = property(last)
  90. def length(self):
  91. return len(self.seq)
  92. length = property(length)
  93. def first_group(self, getter=None):
  94. """
  95. Returns true if this item is the start of a new group,
  96. where groups mean that some attribute has changed. The getter
  97. can be None (the item itself changes), an attribute name like
  98. ``'.attr'``, a function, or a dict key or list index.
  99. """
  100. if self.first:
  101. return True
  102. return self._compare_group(self.item, self.previous, getter)
  103. def last_group(self, getter=None):
  104. """
  105. Returns true if this item is the end of a new group,
  106. where groups mean that some attribute has changed. The getter
  107. can be None (the item itself changes), an attribute name like
  108. ``'.attr'``, a function, or a dict key or list index.
  109. """
  110. if self.last:
  111. return True
  112. return self._compare_group(self.item, self.__next__, getter)
  113. def _compare_group(self, item, other, getter):
  114. if getter is None:
  115. return item != other
  116. elif (isinstance(getter, basestring_)
  117. and getter.startswith('.')):
  118. getter = getter[1:]
  119. if getter.endswith('()'):
  120. getter = getter[:-2]
  121. return getattr(item, getter)() != getattr(other, getter)()
  122. else:
  123. return getattr(item, getter) != getattr(other, getter)
  124. elif hasattr(getter, '__call__'):
  125. return getter(item) != getter(other)
  126. else:
  127. return item[getter] != other[getter]