Merge pull request #1101 from pallets/refactor-loop-context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
don't prefetch next item in loop context
authored by David Lord · committed by GitHub · parents d8820b9, 4d0949b · Browse files · 6 files·+273 added−176 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+273 added−176 removed
- tests:+24 added−20 removed
- other:+249 added−156 removed
Provenance
- Commit
540b260- Tree
da55a67- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d8820b9- Parent 2
4d0949b
6 files changed+273 added−176 removed
modified:jinja2/asyncsupport.py+65 added-55 removed
7 unmodified lines8 9 :copyright: (c) 2017 by the Jinja Team.10 :license: BSD, see LICENSE for more details.11 """12-import sys12 import asyncio13 import inspect14+import sys15 from functools import update_wrapper16 17-from jinja2.utils import concat, internalcode, Markup17 from jinja2.environment import TemplateModule19-from jinja2.runtime import LoopContextBase, _last_iteration18+from jinja2.runtime import LoopContext19+from jinja2.utils import concat20+from jinja2.utils import internalcode21+from jinja2.utils import Markup22+from jinja2.utils import missing23 24 25 async def concat_async(async_gen):26 rv = []162 unmodified lines189 for item in iterable:190 yield item191 192 190-class AsyncLoopContext(LoopContextBase):193+class AsyncLoopContext(LoopContext):194+ _to_iterator = staticmethod(auto_aiter)195 192- 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 = length198-196 @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._length200+201+ 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)207+208 return self._length209 206- def __aiter__(self):207- return AsyncLoopContextIterator(self)210+ @property211+ async def revindex0(self):212+ return await self.length - self.index213 214+ @property215+ async def revindex(self):216+ return await self.length - self.index0217 210-class AsyncLoopContextIterator(object):211- __slots__ = ('context',)218+ async def _peek_next(self):219+ if self._after is not missing:220+ return self._after221 213- def __init__(self, context):214- self.context = context222+ try:223+ self._after = await self._iterator.__anext__()224+ except StopAsyncIteration:225+ self._after = missing226 227+ return self._after228+229+ @property230+ async def last(self):231+ return await self._peek_next() is missing232+233+ @property234+ async def nextitem(self):235+ rv = await self._peek_next()236+237+ if rv is missing:238+ return self._undefined("there is no next item")239+240+ return rv241+242 def __aiter__(self):243 return self244 245 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__()251 252+ self.index0 += 1253+ self._before = self._current254+ self._current = rv255+ return rv, self256 257+258 async 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)267 268 269 patch_all()modified:jinja2/compiler.py+14 added-2 removed
703 unmodified lines704 self.writeline('from jinja2.runtime import ' + ', '.join(exported))705 706 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')709 710 # 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 lines1094 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 ')447 unmodified lines1550 self.visit(node.expr, frame)1551 1552 @optimizeconst1553 def visit_Getattr(self, node, frame):1554+ if self.environment.is_async:1555+ self.write("await auto_await(")1556+1557 self.write('environment.getattr(')1558 self.visit(node.node, frame)1559 self.write(', %r)' % node.attr)1560 1561+ if self.environment.is_async:1562+ self.write(")")1563+1564 @optimizeconst1565 def visit_Getitem(self, node, frame):1566 # slices bypass the environment getitem method.1567 if isinstance(node.arg, nodes.Slice):1 unmodified line1569 self.write('[')1570 self.visit(node.arg, frame)1571 self.write(']')1572 else:1573+ if self.environment.is_async:1574+ self.write("await auto_await(")1575+1576 self.write('environment.getitem(')1577 self.visit(node.node, frame)1578 self.write(', ')1579 self.visit(node.arg, frame)1580 self.write(')')1581 1582+ if self.environment.is_async:1583+ self.write(")")1584+1585 def visit_Slice(self, node, frame):1586 if node.start is not None:1587 self.visit(node.start, frame)1588 self.write(':')157 unmodified linesmodified:jinja2/runtime.py+157 added-94 removed
341 unmodified lines342 rv = Markup(rv)343 return rv344 345 346-class LoopContextBase(object):347- """A loop context for dynamic iteration."""346+@implements_iterator347+class LoopContext:348+ """A wrapper iterable for dynamic ``for`` loops, with information349+ about the loop and iteration.350+ """351 349- _before = _first_iteration350- _current = _first_iteration351- _after = _last_iteration352+ #: Current iteration of the loop, starting at 0.353+ index0 = -1354+355 _length = None356+ _after = missing357+ _current = missing358+ _before = missing359+ _last_changed_value = missing360 354- 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 = missing376 361- 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)380 367- 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.384 374- 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._length390 381- @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)397 387- @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._length399 400 def __len__(self):401 return self.length402 396- @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 + 1407 403- # 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 + 1412 408- 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.416 417+ Requires calculating :attr:`length`.418+ """419+ return self.length - self.index420 416-class LoopContext(LoopContextBase):421+ @property422+ def revindex(self):423+ """Number of iterations from the end of the loop, ending at 1.424 418- 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.index0428 429 @property426- def length(self):430+ def first(self):431+ """Whether this is the first iteration of the loop."""432+ return self.index0 == 0433+434+ 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._after442+443+ self._after = next(self._iterator, missing)444+ return self._after445+446+ @property447+ def last(self):448+ """Whether this is the last iteration of the loop.449+450+ 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 missing455 442- 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")463 445- 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._before465 466+ @property467+ def nextitem(self):468+ """The item in the next iteration. Undefined during the last469+ iteration.470 454-@implements_iterator455-class 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()476 459- def __init__(self, context):460- self.context = context477+ if rv is missing:478+ return self._undefined("there is no next item")479 480+ return rv481+482+ def cycle(self, *args):483+ """Return a value from the given args, cycling through based on484+ the current :attr:`index0`.485+486+ :param args: One or more values to cycle through.487+ """488+ if not args:489+ raise TypeError("no items for cycling given")490+491+ return args[self.index0 % len(args)]492+493+ def changed(self, *value):494+ """Return ``True`` if previously called with a different value495+ (including when called for the first time).496+497+ :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 True502+503+ return False504+505 def __iter__(self):506 return self507 508+ @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)515 516+ self.index0 += 1517+ self._before = self._current518+ self._current = rv519+ return rv, self520 521+ def __call__(self, iterable):522+ """When iterating over nested data, render the body of the loop523+ recursively with the given inner iterable data.524+525+ 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+ )532+533+ return self._recurse(iterable, self._recurse, depth=self.depth)534+535+ def __repr__(self):536+ return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)537+538+539 class Macro(object):540 """Wraps a macro function."""541 542 def __init__(self, environment, func, name, arguments,357 unmodified linesmodified:tests/test_async.py+12 added-20 removed
1 import pytest2 import asyncio3 4 from jinja2 import Template, Environment, DictLoader5+from jinja2.asyncsupport import auto_aiter6 from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \7 UndefinedError8 9 264 unmodified lines274 def test_empty_blocks(self, test_env_async):275 tmpl = test_env_async.from_string('<{% for item in seq %}{% else %}{% endfor %}>')276 assert tmpl.render() == '<>'277 277- def test_context_vars(self, test_env_async):278- slist = [42, 24]279- for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:280- tmpl = test_env_async.from_string('''{% for item in seq -%}281- {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{282- loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{283- loop.length }}###{% endfor %}''')284- one, two, _ = tmpl.render(seq=seq).split('###')285- (one_index, one_index0, one_revindex, one_revindex0, one_first,286- one_last, one_length) = one.split('|')287- (two_index, two_index0, two_revindex, two_revindex0, two_first,288- two_last, two_length) = two.split('|')278+ @pytest.mark.parametrize(279+ "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]280+ )281+ def test_context_vars(self, test_env_async, transform):282+ t = test_env_async.from_string(283+ "{% for item in seq %}{{ loop.index }}|{{ loop.index0 }}"284+ "|{{ loop.revindex }}|{{ loop.revindex0 }}|{{ loop.first }}"285+ "|{{ loop.last }}|{{ loop.length }}\n{% endfor %}"286+ )287+ out = t.render(seq=transform([42, 24]))288+ assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"289 290- assert int(one_index) == 1 and int(two_index) == 2291- assert int(one_index0) == 0 and int(two_index0) == 1292- assert int(one_revindex) == 2 and int(two_revindex) == 1293- assert int(one_revindex0) == 1 and int(two_revindex0) == 0294- assert one_first == 'True' and two_first == 'False'295- assert one_last == 'False' and two_last == 'True'296- assert one_length == two_length == '2'297-290 def test_cycling(self, test_env_async):291 tmpl = test_env_async.from_string('''{% for item in seq %}{{292 loop.cycle('<1>', '<2>') }}{% endfor %}{%293 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')209 unmodified linesmodified:tests/test_runtime.py+12 added
1+import itertools2+3 from jinja2 import Template4 from jinja2.runtime import LoopContext5 6 40 unmodified lines47 def test_loopcontext2():48 in_lst = [10, 11]49 l = LoopContext(reversed(in_lst), None)50 assert l.length == len(in_lst)51+52+53+def test_iterator_not_advanced_early():54+ t = Template("{% for _, g in gs %}{{ loop.index }} {{ g|list }}\n{% endfor %}")55+ out = t.render(gs=itertools.groupby(56+ [(1, "a"), (1, "b"), (2, "c"), (3, "d")], lambda x: x[0]57+ ))58+ # groupby groups depend on the current position of the iterator. If59+ # it was advanced early, the lists would appear empty.60+ assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"modified:CHANGES.rst+13 added-5 removed
3 unmodified lines4 --------------5 6 Unreleased7 8-- Async support is only loaded the first time an9- :class:`~environment.Environment` enables it, in order to avoid a10- slow initial import. :issue:`765`11-- Python 2.6 and 3.3 are not supported anymore.8+- Python 2.6, 3.3, and 3.4 are not supported anymore.12-- The ``map`` filter in async mode now automatically awaits9 - Added a new ``ChainableUndefined`` class to support getitem and10 getattr on an undefined object. :issue:`977`11 - Allow ``{%+`` syntax (with NOP behavior) when ``lstrip_blocks`` is12 disabled. :issue:`748`29 unmodified lines42 :class:`StrictUndefined`). :issue:`710`, :pr:`1079`43 - Fix behavior of ``loop`` control variables such as ``length`` and44 ``revindex0`` when looping over a generator. :issue:`459, 751, 794`,45 :pr:`993`46+- Async support is only loaded the first time an environment enables47+ it, in order to avoid a slow initial import. :issue:`765`48+- In async environments, the ``|map`` filter will await the filter49+ call if needed. :pr:`913`50+- In for loops that access ``loop`` attributes, the iterator is not51+ advanced ahead of the current iteration unless ``length``,52+ ``revindex``, ``nextitem``, or ``last`` are accessed. This makes it53+ less likely to break ``groupby`` results. :issue:`555`, :pr:`1101`54+- In async environments, the ``loop`` attributes ``length`` and55+ ``revindex`` work for async iterators. :pr:`1101`56+- In async environments, values from attribute/property access will57+ be awaited if needed. :pr:`1101`58 - ``PackageLoader`` doesn't depend on setuptools or pkg_resources.59 :issue:`970`60 - Support :class:`os.PathLike` objects in61 :class:`~loader.FileSystemLoader` and :class:`~loader.ModuleLoader`.649 unmodified lines