A loop context for dynamic iteration.
| 349 | |
| 350 | |
| 351 | class LoopContextBase(object): |
| 352 | """A loop context for dynamic iteration.""" |
| 353 | |
| 354 | _before = _first_iteration |
| 355 | _current = _first_iteration |
| 356 | _after = _last_iteration |
| 357 | _length = None |
| 358 | |
| 359 | def __init__(self, undefined, recurse=None, depth0=0): |
| 360 | self._undefined = undefined |
| 361 | self._recurse = recurse |
| 362 | self.index0 = -1 |
| 363 | self.depth0 = depth0 |
| 364 | self._last_checked_value = missing |
| 365 | |
| 366 | def cycle(self, *args): |
| 367 | """Cycles among the arguments with the current loop index.""" |
| 368 | if not args: |
| 369 | raise TypeError('no items for cycling given') |
| 370 | return args[self.index0 % len(args)] |
| 371 | |
| 372 | def changed(self, *value): |
| 373 | """Checks whether the value has changed since the last call.""" |
| 374 | if self._last_checked_value != value: |
| 375 | self._last_checked_value = value |
| 376 | return True |
| 377 | return False |
| 378 | |
| 379 | first = property(lambda x: x.index0 == 0) |
| 380 | last = property(lambda x: x._after is _last_iteration) |
| 381 | index = property(lambda x: x.index0 + 1) |
| 382 | revindex = property(lambda x: x.length - x.index0) |
| 383 | revindex0 = property(lambda x: x.length - x.index) |
| 384 | depth = property(lambda x: x.depth0 + 1) |
| 385 | |
| 386 | @property |
| 387 | def previtem(self): |
| 388 | if self._before is _first_iteration: |
| 389 | return self._undefined('there is no previous item') |
| 390 | return self._before |
| 391 | |
| 392 | @property |
| 393 | def nextitem(self): |
| 394 | if self._after is _last_iteration: |
| 395 | return self._undefined('there is no next item') |
| 396 | return self._after |
| 397 | |
| 398 | def __len__(self): |
| 399 | return self.length |
| 400 | |
| 401 | @internalcode |
| 402 | def loop(self, iterable): |
| 403 | if self._recurse is None: |
| 404 | raise TypeError('Tried to call non recursive loop. Maybe you ' |
| 405 | "forgot the 'recursive' modifier.") |
| 406 | return self._recurse(iterable, self._recurse, self.depth0 + 1) |
| 407 | |
| 408 | # a nifty trick to enhance the error message if someone tried to call |
nothing calls this directly
no test coverage detected
searching dependent graphs…