Skip to content
Myr

don't prefetch next item in loop context

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent d8820b9 · Browse files · 3 files+224 added−151 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+224 added−151 removed

  • other:+224 added−151 removed

3 files+224 added−151 removed

modified:jinja2/asyncsupport.py+65 added-55 removed
7 unmodified lines
89 :copyright: (c) 2017 by the Jinja Team.10 :license: BSD, see LICENSE for more details.11"""12import sys12import asyncio13import inspect14import sys15from functools import update_wrapper1617from jinja2.utils import concat, internalcode, Markup17from jinja2.environment import TemplateModule19from jinja2.runtime import LoopContextBase, _last_iteration18from jinja2.runtime import LoopContext19from jinja2.utils import concat20from jinja2.utils import internalcode21from jinja2.utils import Markup22from jinja2.utils import missing232425async def concat_async(async_gen):26 rv = []
162 unmodified lines
189 for item in iterable:190 yield item191192190class AsyncLoopContext(LoopContextBase):193class AsyncLoopContext(LoopContext):194 _to_iterator = staticmethod(auto_aiter)195192 def __init__(self, async_iterator, undefined, after, length, recurse=None,193 depth0=0):194 LoopContextBase.__init__(self, undefined, recurse, depth0)195 self._async_iterator = async_iterator196 self._after = after197 self._length = length198196 @property200 def length(self):201 if self._length is None:202 raise TypeError('Loop length for some iterators cannot be '203 'lazily calculated in async mode')197 async def length(self):198 if self._length is not None:199 return self._length200201 try:202 self._length = len(self._iterable)203 except TypeError:204 iterable = [x async for x in self._iterator]205 self._iterator = self._to_iterator(iterable)206 self._length = len(iterable) + self.index + (self._after is not missing)207208 return self._length209206 def __aiter__(self):207 return AsyncLoopContextIterator(self)210 @property211 async def revindex0(self):212 return await self.length - self.index213214 @property215 async def revindex(self):216 return await self.length - self.index0217210class AsyncLoopContextIterator(object):211 __slots__ = ('context',)218 async def _peek_next(self):219 if self._after is not missing:220 return self._after221213 def __init__(self, context):214 self.context = context222 try:223 self._after = await self._iterator.__anext__()224 except StopAsyncIteration:225 self._after = missing226227 return self._after228229 @property230 async def last(self):231 return await self._peek_next() is missing232233 @property234 async def nextitem(self):235 rv = await self._peek_next()236237 if rv is missing:238 return self._undefined("there is no next item")239240 return rv241242 def __aiter__(self):243 return self244245 async def __anext__(self):220 ctx = self.context221 ctx.index0 += 1222 if ctx._after is _last_iteration:223 raise StopAsyncIteration()224 ctx._before = ctx._current225 ctx._current = ctx._after226 try:227 ctx._after = await ctx._async_iterator.__anext__()228 except StopAsyncIteration:229 ctx._after = _last_iteration230 return ctx._current, ctx246 if self._after is not missing:247 rv = self._after248 self._after = missing249 else:250 rv = await self._iterator.__anext__()251252 self.index0 += 1253 self._before = self._current254 self._current = rv255 return rv, self256257258async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):234 # Length is more complicated and less efficient in async mode. The235 # reason for this is that we cannot know if length will be used236 # upfront but because length is a property we cannot lazily execute it237 # later. This means that we need to buffer it up and measure :(238 #239 # We however only do this for actual iterators, not for async240 # iterators as blocking here does not seem like the best idea in the241 # world.242 try:243 length = len(iterable)244 except (TypeError, AttributeError):245 if not hasattr(iterable, '__aiter__'):246 iterable = tuple(iterable)247 length = len(iterable)248 else:249 length = None250 async_iterator = auto_aiter(iterable)251 try:252 after = await async_iterator.__anext__()253 except StopAsyncIteration:254 after = _last_iteration255 return AsyncLoopContext(async_iterator, undefined, after, length, recurse,256 depth0)259 import warnings260 warnings.warn(261 "This template must be recompiled with at least Jinja 2.11, or"262 " it will fail in 3.0.",263 DeprecationWarning,264 stacklevel=2,265 )266 return AsyncLoopContext(iterable, undefined, recurse, depth0)267268269patch_all()
modified:jinja2/compiler.py+2 added-2 removed
703 unmodified lines
704 self.writeline('from jinja2.runtime import ' + ', '.join(exported))705706 if self.environment.is_async:707 self.writeline('from jinja2.asyncsupport import auto_await, '708 'auto_aiter, make_async_loop_context')708 'auto_aiter, AsyncLoopContext')709710 # if we want a deferred initialization we cannot move the711 # environment into a local name712 envenv = not self.defer_init and ', environment=environment' or ''
381 unmodified lines
1094 self.writeline(self.environment.is_async and 'async for ' or 'for ', node)1095 self.visit(node.target, loop_frame)1096 if extended_loop:1097 if self.environment.is_async:1098 self.write(', %s in await make_async_loop_context(' % loop_ref)1098 self.write(', %s in AsyncLoopContext(' % loop_ref)1099 else:1100 self.write(', %s in LoopContext(' % loop_ref)1101 else:1102 self.write(' in ')
631 unmodified lines
modified:jinja2/runtime.py+157 added-94 removed
341 unmodified lines
342 rv = Markup(rv)343 return rv344345346class LoopContextBase(object):347 """A loop context for dynamic iteration."""346@implements_iterator347class LoopContext:348 """A wrapper iterable for dynamic ``for`` loops, with information349 about the loop and iteration.350 """351349 _before = _first_iteration350 _current = _first_iteration351 _after = _last_iteration352 #: Current iteration of the loop, starting at 0.353 index0 = -1354355 _length = None356 _after = missing357 _current = missing358 _before = missing359 _last_changed_value = missing360354 def __init__(self, undefined, recurse=None, depth0=0):361 def __init__(self, iterable, undefined, recurse=None, depth0=0):362 """363 :param iterable: Iterable to wrap.364 :param undefined: :class:`Undefined` class to use for next and365 previous items.366 :param recurse: The function to render the loop body when the367 loop is marked recursive.368 :param depth0: Incremented when looping recursively.369 """370 self._iterable = iterable371 self._iterator = self._to_iterator(iterable)372 self._undefined = undefined373 self._recurse = recurse357 self.index0 = -1374 #: How many levels deep a recursive loop currently is, starting at 0.375 self.depth0 = depth0359 self._last_checked_value = missing376361 def cycle(self, *args):362 """Cycles among the arguments with the current loop index."""363 if not args:364 raise TypeError('no items for cycling given')365 return args[self.index0 % len(args)]377 @staticmethod378 def _to_iterator(iterable):379 return iter(iterable)380367 def changed(self, *value):368 """Checks whether the value has changed since the last call."""369 if self._last_checked_value != value:370 self._last_checked_value = value371 return True372 return False381 @property382 def length(self):383 """Length of the iterable.384374 first = property(lambda x: x.index0 == 0)375 last = property(lambda x: x._after is _last_iteration)376 index = property(lambda x: x.index0 + 1)377 revindex = property(lambda x: x.length - x.index0)378 revindex0 = property(lambda x: x.length - x.index)379 depth = property(lambda x: x.depth0 + 1)385 If the iterable is a generator or otherwise does not have a386 size, it is eagerly evaluated to get a size.387 """388 if self._length is not None:389 return self._length390381 @property382 def previtem(self):383 if self._before is _first_iteration:384 return self._undefined('there is no previous item')385 return self._before391 try:392 self._length = len(self._iterable)393 except TypeError:394 iterable = list(self._iterator)395 self._iterator = self._to_iterator(iterable)396 self._length = len(iterable) + self.index + (self._after is not missing)397387 @property388 def nextitem(self):389 if self._after is _last_iteration:390 return self._undefined('there is no next item')391 return self._after398 return self._length399400 def __len__(self):401 return self.length402396 @internalcode397 def loop(self, iterable):398 if self._recurse is None:399 raise TypeError('Tried to call non recursive loop. Maybe you '400 "forgot the 'recursive' modifier.")401 return self._recurse(iterable, self._recurse, self.depth0 + 1)403 @property404 def depth(self):405 """How many levels deep a recursive loop currently is, starting at 1."""406 return self.depth0 + 1407403 # a nifty trick to enhance the error message if someone tried to call404 # the loop without or with too many arguments.405 __call__ = loop406 del loop408 @property409 def index(self):410 """Current iteration of the loop, starting at 1."""411 return self.index0 + 1412408 def __repr__(self):409 return '<%s %r/%r>' % (410 self.__class__.__name__,411 self.index,412 self.length413 )413 @property414 def revindex0(self):415 """Number of iterations from the end of the loop, ending at 0.416417 Requires calculating :attr:`length`.418 """419 return self.length - self.index420416class LoopContext(LoopContextBase):421 @property422 def revindex(self):423 """Number of iterations from the end of the loop, ending at 1.424418 def __init__(self, iterable, undefined, recurse=None, depth0=0):419 LoopContextBase.__init__(self, undefined, recurse, depth0)420 self._iterator = iter(iterable)421 self._iterations_done_count = 0422 self._length = None423 self._after = self._safe_next()425 Requires calculating :attr:`length`.426 """427 return self.length - self.index0428429 @property426 def length(self):430 def first(self):431 """Whether this is the first iteration of the loop."""432 return self.index0 == 0433434 def _peek_next(self):435 """Return the next element in the iterable, or :data:`missing`436 if the iterable is exhausted. Only peeks one item ahead, caching437 the result in :attr:`_last` for use in subsequent checks. The438 cache is reset when :meth:`__next__` is called.439 """428 Getting length of an iterator is a costly operation which requires extra memory429 and traversing in linear time. So make it an on demand param that iterates from430 the point onwards of the iterator and accounts for iterated elements.440 if self._after is not missing:441 return self._after442443 self._after = next(self._iterator, missing)444 return self._after445446 @property447 def last(self):448 """Whether this is the last iteration of the loop.449450 Causes the iterable to advance early. See451 :func:`itertools.groupby` for issues this can cause.452 The :func:`groupby` filter avoids that issue.453 """432 if self._length is None:433 # if was not possible to get the length of the iterator when434 # the loop context was created (ie: iterating over a generator)435 # we have to convert the iterable into a sequence and use the436 # length of that + the number of iterations so far.437 iterable = tuple(self._iterator)438 self._iterator = iter(iterable)439 self._length = len(iterable) + self._iterations_done_count440 return self._length454 return self._peek_next() is missing455442 def __iter__(self):443 return LoopContextIterator(self)456 @property457 def previtem(self):458 """The item in the previous iteration. Undefined during the459 first iteration.460 """461 if self.first:462 return self._undefined("there is no previous item")463445 def _safe_next(self):446 try:447 tmp = next(self._iterator)448 self._iterations_done_count += 1449 return tmp450 except StopIteration:451 return _last_iteration464 return self._before465466 @property467 def nextitem(self):468 """The item in the next iteration. Undefined during the last469 iteration.470454@implements_iterator455class LoopContextIterator(object):456 """The iterator for a loop context."""457 __slots__ = ('context',)471 Causes the iterable to advance early. See472 :func:`itertools.groupby` for issues this can cause.473 The :func:`groupby` filter avoids that issue.474 """475 rv = self._peek_next()476459 def __init__(self, context):460 self.context = context477 if rv is missing:478 return self._undefined("there is no next item")479480 return rv481482 def cycle(self, *args):483 """Return a value from the given args, cycling through based on484 the current :attr:`index0`.485486 :param args: One or more values to cycle through.487 """488 if not args:489 raise TypeError("no items for cycling given")490491 return args[self.index0 % len(args)]492493 def changed(self, *value):494 """Return ``True`` if previously called with a different value495 (including when called for the first time).496497 :param value: One or more values to compare to the last call.498 """499 if self._last_changed_value != value:500 self._last_changed_value = value501 return True502503 return False504505 def __iter__(self):506 return self507508 @internalcode509 def __next__(self):466 ctx = self.context467 ctx.index0 += 1468 if ctx._after is _last_iteration:469 raise StopIteration()470 ctx._before = ctx._current471 ctx._current = ctx._after472 ctx._after = ctx._safe_next()473 return ctx._current, ctx510 if self._after is not missing:511 rv = self._after512 self._after = missing513 else:514 rv = next(self._iterator)515516 self.index0 += 1517 self._before = self._current518 self._current = rv519 return rv, self520521 def __call__(self, iterable):522 """When iterating over nested data, render the body of the loop523 recursively with the given inner iterable data.524525 The loop must have the ``recursive`` marker for this to work.526 """527 if self._recurse is None:528 raise TypeError(529 "The loop must have the 'recursive' marker to be"530 " called recursively."531 )532533 return self._recurse(iterable, self._recurse, depth=self.depth)534535 def __repr__(self):536 return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)537538539class Macro(object):540 """Wraps a macro function."""541542 def __init__(self, environment, func, name, arguments,
357 unmodified lines