Skip to content
Myr

Implement consistent scoping for sets in loops

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

While technically this applies to any scope and not just for loops it comes up most commonly in the context of for loops. This now defines the behavior for scoping in a way that is consistent but different than it was in the past. There is an ongoing conversation if we should keep it that way or not. References #641

authored by Armin Ronacher · committed by Armin Ronacher · parent b557eca · Browse files · 2 files+23 added−2 removed
This commit

State

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

Diff stats

2 files+23 added−2 removed

  • tests:+9 added−0 removed
  • other:+14 added−2 removed

2 files+23 added−2 removed

modified:jinja2/idtracking.py+14 added-2 removed
71 unmodified lines
72 rv.stores = self.stores.copy()73 return rv7475 def store(self, name):76 # We already have that name locally, so we can just bail76 self.stores.add(name)7778 # If we have not see the name referenced yet, we need to figure79 # out what to set it to.80 if name not in self.refs:81 # If there is a parent scope we check if the name has a82 # reference there. If it does it means we might have to alias83 # to a variable there.84 if self.parent is not None:85 outer_ref = self.parent.find_ref(name)86 if outer_ref is not None:87 self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))88 return8990 # Otherwise we can just set it to undefined.91 self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))79 self.stores.add(name)9293 def declare_parameter(self, name):94 self.stores.add(name)95 return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))
165 unmodified lines
modified:tests/test_core_tags.py+9 added
197 unmodified lines
198 tmpl = env.from_string('{% for a, b, c in [[1, 2, 3]] %}'199 '{{ a }}|{{ b }}|{{ c }}{% endfor %}')200 assert tmpl.render() == '1|2|3'201202 def test_intended_scoping_with_set(self, env):203 tmpl = env.from_string('{% for item in seq %}{{ x }}'204 '{% set x = item %}{{ x }}{% endfor %}')205 assert tmpl.render(x=0, seq=[1, 2, 3]) == '010203'206207 tmpl = env.from_string('{% set x = 9 %}{% for item in seq %}{{ x }}'208 '{% set x = item %}{{ x }}{% endfor %}')209 assert tmpl.render(x=0, seq=[1, 2, 3]) == '919293'210211212@pytest.mark.core_tags213@pytest.mark.if_condition214class TestIfCondition(object):215
150 unmodified lines