| 194 | |
| 195 | |
| 196 | class _regen(UserList, list): |
| 197 | # must be subclass of list so that json can encode. |
| 198 | |
| 199 | def __init__(self, it): |
| 200 | # pylint: disable=super-init-not-called |
| 201 | # UserList creates a new list and sets .data, so we don't |
| 202 | # want to call init here. |
| 203 | self.__it = it |
| 204 | self.__consumed = [] |
| 205 | self.__done = False |
| 206 | |
| 207 | def __reduce__(self): |
| 208 | return list, (self.data,) |
| 209 | |
| 210 | def map(self, func): |
| 211 | self.__consumed = [func(el) for el in self.__consumed] |
| 212 | self.__it = map(func, self.__it) |
| 213 | |
| 214 | def __length_hint__(self): |
| 215 | return self.__it.__length_hint__() |
| 216 | |
| 217 | def __lookahead_consume(self, limit=None): |
| 218 | if not self.__done and (limit is None or limit > 0): |
| 219 | it = iter(self.__it) |
| 220 | try: |
| 221 | now = next(it) |
| 222 | except StopIteration: |
| 223 | return |
| 224 | self.__consumed.append(now) |
| 225 | # Maintain a single look-ahead to ensure we set `__done` when the |
| 226 | # underlying iterator gets exhausted |
| 227 | while not self.__done: |
| 228 | try: |
| 229 | next_ = next(it) |
| 230 | self.__consumed.append(next_) |
| 231 | except StopIteration: |
| 232 | self.__done = True |
| 233 | break |
| 234 | finally: |
| 235 | yield now |
| 236 | now = next_ |
| 237 | # We can break out when `limit` is exhausted |
| 238 | if limit is not None: |
| 239 | limit -= 1 |
| 240 | if limit <= 0: |
| 241 | break |
| 242 | |
| 243 | def __iter__(self): |
| 244 | # Track our own position in `__consumed` rather than relying on the |
| 245 | # shared look-ahead generator, so that other consumers (``len()``, |
| 246 | # indexing or a nested loop) exhausting the underlying iterator |
| 247 | # midway through don't cut this iteration short. |
| 248 | it = None |
| 249 | index = 0 |
| 250 | # Items already concretised are yielded without looking ahead, only |
| 251 | # once we pull from the underlying iterator ourselves do we look |
| 252 | # ahead, so a lazy generator isn't consumed any earlier than needed |
| 253 | # (see #3021). |