Skip to content
Myr

Add support for namespaces in tuple assignment

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

This fixes a bug that existed because namespaces within `{% set %}` were treated as a special case. This special case had the side-effect of bypassing the code which allows for tuples to be assigned to. The solution was to make tuple handling (and by extension, primary token handling) aware of namespaces so that namespace tokens can be handled appropriately. This is handled in a backwards-compatible way which ensures that we do not try to parse namespace tokens when we otherwise would be expecting to parse out name tokens with attributes. Namespace instance checks are moved earlier, and deduplicated, so that all checks are done before the assignment. Otherwise, the check could be emitted in the middle of the tuple.

authored by Kevin Brown-Silva · committed by David Lord · parent 1d55cdd · Browse files · 5 files+46 added−20 removed
This commit

State

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

Diff stats

5 files+46 added−20 removed

  • tests:+8 added−0 removed
  • other:+38 added−20 removed

5 files+46 added−20 removed

modified:docs/templates.rst+3 added
1676 unmodified lines
1677 Found item having something: {{ ns.found }}16781679 .. versionadded:: 2.1016801681 .. versionchanged:: 3.21682 Namespace attributes can be assigned to in multiple assignment.168316841685Extensions1686----------16871688.. py:currentmodule:: jinja2
277 unmodified lines
modified:src/jinja2/compiler.py+16 added-7 removed
1579 unmodified lines
1580 self.outdent()15811582 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:1583 self.push_assign_tracking()15841585 # NSRef can only ever be used during assignment so we need to check1586 # to make sure that it is only being used to assign using a Namespace.1587 # This check is done here because it is used an expression during the1588 # assignment and therefore cannot have this check done when the NSRef1589 # node is visited1590 for nsref in node.find_all(nodes.NSRef):1591 ref = frame.symbols.ref(nsref.name)1592 self.writeline(f"if not isinstance({ref}, Namespace):")1593 self.indent()1594 self.writeline(1595 "raise TemplateRuntimeError"1596 '("cannot assign attribute on non-namespace object")'1597 )1598 self.outdent()15991600 self.newline(node)1601 self.visit(node.target, frame)1602 self.write(" = ")1603 self.visit(node.node, frame)
52 unmodified lines
1656 # NSRefs can only be used to store values; since they use the normal1657 # `foo.bar` notation they will be parsed as a normal attribute access1658 # when used anywhere but in a `set` context1659 ref = frame.symbols.ref(node.name)1644 self.writeline(f"if not isinstance({ref}, Namespace):")1645 self.indent()1646 self.writeline(1647 "raise TemplateRuntimeError"1648 '("cannot assign attribute on non-namespace object")'1649 )1650 self.outdent()1660 self.writeline(f"{ref}[{node.attr!r}]")16611662 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:1663 val = node.as_const(frame.eval_ctx)
327 unmodified lines
modified:src/jinja2/parser.py+17 added-13 removed
485 unmodified lines
486 `with_namespace` is enabled, a namespace assignment may be parsed.487 """488 target: nodes.Expr489490 if with_namespace and self.stream.look().type == "dot":490 if name_only:491 token = self.stream.expect("name")492 next(self.stream) # dot493 attr = self.stream.expect("name")494 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)495 elif name_only:496 token = self.stream.expect("name")492 target = nodes.Name(token.value, "store", lineno=token.lineno)493 else:494 if with_tuple:495 target = self.parse_tuple(501 simplified=True, extra_end_rules=extra_end_rules496 simplified=True,497 extra_end_rules=extra_end_rules,498 with_namespace=with_namespace,499 )500 else:504 target = self.parse_primary()501 target = self.parse_primary(with_namespace=with_namespace)502503 target.set_ctx("store")504505 if not target.can_assign():
133 unmodified lines
639 if with_filter:640 node = self.parse_filter_expr(node)641 return node642646 def parse_primary(self) -> nodes.Expr:643 def parse_primary(self, with_namespace: bool = False) -> nodes.Expr:644 token = self.stream.current645 node: nodes.Expr646 if token.type == "name":647 if token.value in ("true", "false", "True", "False"):648 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)649 elif token.value in ("none", "None"):650 node = nodes.Const(None, lineno=token.lineno)651 elif with_namespace and self.stream.look().type == "dot":652 next(self.stream) # token653 next(self.stream) # dot654 attr = self.stream.current655 node = nodes.NSRef(token.value, attr.value, lineno=token.lineno)656 else:657 node = nodes.Name(token.value, "load", lineno=token.lineno)658 next(self.stream)659 elif token.type == "string":
24 unmodified lines
684 simplified: bool = False,685 with_condexpr: bool = True,686 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,687 explicit_parentheses: bool = False,688 with_namespace: bool = False,689 ) -> t.Union[nodes.Tuple, nodes.Expr]:690 """Works like `parse_expression` but if multiple expressions are691 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.692 This method could also return a regular expression instead of a tuple
13 unmodified lines
706 tuple is a valid expression or not.707 """708 lineno = self.stream.current.lineno709 if simplified:707 parse = self.parse_primary708 elif with_condexpr:709 parse = self.parse_expression710711 def parse() -> nodes.Expr:712 return self.parse_primary(with_namespace=with_namespace)713714 else:715716 def parse() -> nodes.Expr:713 return self.parse_expression(with_condexpr=False)717 return self.parse_expression(with_condexpr=with_condexpr)718719 args: t.List[nodes.Expr] = []720 is_tuple = False721
324 unmodified lines
modified:tests/test_core_tags.py+8 added
536 unmodified lines
537 "{{ ns.a }}|{{ ns.b }}"538 )539 assert tmpl.render() == "13|37"540541 def test_namespace_set_tuple(self, env_trim):542 tmpl = env_trim.from_string(543 "{% set ns = namespace(a=12, b=36) %}"544 "{% set ns.a, ns.b = ns.a + 1, ns.b + 1 %}"545 "{{ ns.a }}|{{ ns.b }}"546 )547 assert tmpl.render() == "13|37"548549 def test_block_escaping_filtered(self):550 env = Environment(autoescape=True)551 tmpl = env.from_string(552 "{% set foo | trim %}<em>{{ test }}</em> {% endset %}foo: {{ foo }}"
51 unmodified lines
modified:CHANGES.rst+2 added
41 unmodified lines
42- Improve annotations for methods returning copies. :pr:`1880`43- ``urlize`` does not add ``mailto:`` to values like `@a@b`. :pr:`1870`44- Tests decorated with `@pass_context`` can be used with the ``|select``45 filter. :issue:`1624`46- Using ``set`` for multiple assignment (``a, b = 1, 2``) does not fail when the47 target is a namespace attribute. :issue:`1413`484950Version 3.1.451-------------
994 unmodified lines