Merge pull request #993 from aayushuppal/loop_fix
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix for Loop properties revindex and revindex0 still wrong in Jinja2 2.10 #794
authored by David Lord · committed by GitHub · parents 468b2df, ef1a4c6 · Browse files · 3 files·+62 added−12 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+62 added−12 removed
- tests:+48 added−0 removed
- other:+14 added−12 removed
Provenance
- Commit
81b3224- Tree
76873a0- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
468b2df- Parent 2
ef1a4c6
3 files changed+62 added−12 removed
modified:jinja2/runtime.py+11 added-12 removed
416 unmodified lines417 418 def __init__(self, iterable, undefined, recurse=None, depth0=0):419 LoopContextBase.__init__(self, undefined, recurse, depth0)420 self._iterator = iter(iterable)421-422- # try to get the length of the iterable early. This must be done423- # here because there are some broken iterators around where there424- # __len__ is the number of iterations left (i'm looking at your425- # listreverseiterator!).426- try:427- self._length = len(iterable)428- except (TypeError, AttributeError):429- self._length = None421+ self._iterations_done_count = 0422+ self._length = None423 self._after = self._safe_next()424 425 @property426 def length(self):427+ """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.431+ """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)441- iterations_done = self.index0 + 2442- self._length = len(iterable) + iterations_done439+ self._length = len(iterable) + self._iterations_done_count440 return self._length441 442 def __iter__(self):443 return LoopContextIterator(self)444 445 def _safe_next(self):446 try:450- return next(self._iterator)447+ tmp = next(self._iterator)448+ self._iterations_done_count += 1449+ return tmp450 except StopIteration:451 return _last_iteration452 453 383 unmodified linesadded:tests/test_runtime.py+48 added
1+from jinja2 import Template2+from jinja2.runtime import LoopContext3+4+5+TEST_IDX_TEMPLATE_STR_1 = (6+ "[{% for i in lst|reverse %}"7+ + "(len={{ loop.length }}, revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }})"8+ + "{% endfor %}]"9+)10+11+12+TEST_IDX0_TEMPLATE_STR_1 = (13+ "[{% for i in lst|reverse %}"14+ + "(len={{ loop.length }}, revindex0={{ loop.revindex0 }}, index0={{ loop.index0 }}, val={{ i }})"15+ + "{% endfor %}]"16+)17+18+19+def test_loop_idx():20+ t = Template(TEST_IDX_TEMPLATE_STR_1)21+ lst = [10]22+ excepted_render = "[(len=1, revindex=1, index=1, val=10)]"23+ assert excepted_render == t.render(lst=lst)24+25+26+def test_loop_idx0():27+ t = Template(TEST_IDX0_TEMPLATE_STR_1)28+ lst = [10]29+ excepted_render = "[(len=1, revindex0=0, index0=0, val=10)]"30+ assert excepted_render == t.render(lst=lst)31+32+33+def test_loopcontext0():34+ in_lst = []35+ l = LoopContext(reversed(in_lst), None)36+ assert l.length == len(in_lst)37+38+39+def test_loopcontext1():40+ in_lst = [10]41+ l = LoopContext(reversed(in_lst), None)42+ assert l.length == len(in_lst)43+44+45+def test_loopcontext2():46+ in_lst = [10, 11]47+ l = LoopContext(reversed(in_lst), None)48+ assert l.length == len(in_lst)modified:CHANGES.rst+3 added
42 unmodified lines43 in a ``{{ 'foo' if bar }}`` expression, regardless of the44 environment's ``undefined`` class. Omitting the ``else`` clause is a45 valid shortcut and should not raise an error when using46 :class:`StrictUndefined`). :issue:`710`, :pr:`1079`47+- Fix behavior of ``loop`` control variables such as ``length`` and48+ ``revindex0`` when looping over a generator. :issue:`459, 751, 794`,49+ :pr:`993`50 51 52 Version 2.10.353 --------------629 unmodified lines