Skip to content
Myr

Merge pull request #684 from ThiefMaster/set-namespaces

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

Add namespace objects that support attribute assignment

authored by Adrian · committed by GitHub · parents b73cb48, e0475f9 · Browse files · 12 files+168 added−11 removed
This commit

State

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

Diff stats

12 files+168 added−11 removed

  • tests:+55 added−2 removed
  • other:+113 added−9 removed

12 files+168 added−11 removed

modified:docs/api.rst+2 added
685 unmodified lines
686 The reason why the filename and error message are bytestrings and not687 unicode strings is that Python 2.x is not using unicode for exceptions688 and tracebacks as well as the compiler. This will change with Python 3.689690.. autoexception:: jinja2.TemplateRuntimeError691692.. autoexception:: jinja2.TemplateAssertionError693694695.. _writing-filters:
230 unmodified lines
modified:docs/templates.rst+41 added
906 unmodified lines
907 {% else %}908 did not iterate909 {% endfor %}910911 As of version 2.10 more complex use cases can be handled using namespace912 objects which allow propagating of changes across scopes::913914 {% set ns = namespace(found=false) %}915 {% for item in items %}916 {% if item.check_something() %}917 {% set ns.found = true %}918 {% endif %}919 * {{ item.title }}920 {% endfor %}921 Found item having something: {{ ns.found }}922923 Note hat the ``obj.attr`` notation in the `set` tag is only allowed for924 namespace objects; attempting to assign an attribute on any other object925 will raise an exception.926927 .. versionadded:: 2.10 Added support for namespace objects928929930Block Assignments931~~~~~~~~~~~~~~~~~932933.. versionadded:: 2.8
483 unmodified lines
1417 {% endif %}14181419 .. versionadded:: 2.114201421.. class:: namespace(...)14221423 Creates a new container that allows attribute assignment using the1424 ``{% set %}`` tag::14251426 {% set ns = namespace() %}1427 {% set ns.foo = 'bar' %}14281429 The main purpose of this is to allow carrying a value from within a loop1430 body to an outer scope. Initial values can be provided as a dict, as1431 keyword arguments, or both (same behavior as Python's `dict` constructor)::14321433 {% set ns = namespace(found=false) %}1434 {% for item in items %}1435 {% if item.check_something() %}1436 {% set ns.found = true %}1437 {% endif %}1438 * {{ item.title }}1439 {% endfor %}1440 Found item having something: {{ ns.found }}14411442 .. versionadded:: 2.10144314441445Extensions1446----------14471448The following sections cover the built-in Jinja2 extensions that may be
192 unmodified lines
modified:jinja2/__init__.py+2 added-1 removed
46 unmodified lines
4748# exceptions49from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \51 TemplateAssertionError51 TemplateAssertionError, TemplateRuntimeError5253# decorators and public utilities54from jinja2.filters import environmentfilter, contextfilter, \55 evalcontextfilter
7 unmodified lines
63 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache',64 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',65 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',66 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67 'TemplateRuntimeError',68 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',69 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',70 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',71 'select_autoescape',
12 unmodified lines
modified:jinja2/compiler.py+12 added
1401 unmodified lines
1402 return14031404 self.write(ref)14051406 def visit_NSRef(self, node, frame):1407 # NSRefs can only be used to store values; since they use the normal1408 # `foo.bar` notation they will be parsed as a normal attribute access1409 # when used anywhere but in a `set` context1410 ref = frame.symbols.ref(node.name)1411 self.writeline('if not isinstance(%s, Namespace):' % ref)1412 self.indent()1413 self.writeline('raise TemplateRuntimeError(%r)' %1414 'cannot assign attribute on non-namespace object')1415 self.outdent()1416 self.writeline('%s[%r]' % (ref, node.attr))14171418 def visit_Const(self, node, frame):1419 val = node.as_const(frame.eval_ctx)1420 if isinstance(val, float):1421 self.write(str(val))
288 unmodified lines
modified:jinja2/defaults.py+3 added-2 removed
7 unmodified lines
8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._compat import range_type12from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner12from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner, Namespace131415# defaults for the parser / lexer16BLOCK_START_STRING = '{%'
17 unmodified lines
34 'range': range_type,35 'dict': dict,36 'lipsum': generate_lorem_ipsum,37 'cycler': Cycler,38 'joiner': Joiner38 'joiner': Joiner,39 'namespace': Namespace40}414243# default policies
12 unmodified lines
modified:jinja2/idtracking.py+3 added
213 unmodified lines
214 self.symbols.store(node.name)215 elif node.ctx == 'load':216 self.symbols.load(node.name)217218 def visit_NSRef(self, node, **kwargs):219 self.symbols.load(node.name)220221 def visit_If(self, node, **kwargs):222 self.visit(node.test, **kwargs)223224 original_symbols = self.symbols
61 unmodified lines
modified:jinja2/nodes.py+12 added
463 unmodified lines
464 return self.name not in ('true', 'false', 'none',465 'True', 'False', 'None')466467468class NSRef(Expr):469 """Reference to a namespace value assignment"""470 fields = ('name', 'attr')471472 def can_assign(self):473 # We don't need any special checks here; NSRef assignments have a474 # runtime check to ensure the target is a namespace object which will475 # have been checked already as it is created using a normal assignment476 # which goes through a `Name` node.477 return True478479480class Literal(Expr):481 """Baseclass for literals."""482 abstract = True483
484 unmodified lines
modified:jinja2/parser.py+10 added-4 removed
174 unmodified lines
175176 def parse_set(self):177 """Parse an assign statement."""178 lineno = next(self.stream).lineno179 target = self.parse_assign_target()179 target = self.parse_assign_target(with_namespace=True)180 if self.stream.skip_if('assign'):181 expr = self.parse_tuple()182 return nodes.Assign(target, expr, lineno=lineno)183 body = self.parse_statements(('name:endset',),
210 unmodified lines
394 node.nodes.append(self.parse_expression())395 return node396397 def parse_assign_target(self, with_tuple=True, name_only=False,398 extra_end_rules=None):398 extra_end_rules=None, with_namespace=False):399 """Parse an assignment target. As Jinja2 allows assignments to400 tuples, this function can parse all allowed assignment targets. Per401 default assignments to tuples are parsed, that can be disable however402 by setting `with_tuple` to `False`. If only assignments to names are403 wanted `name_only` can be set to `True`. The `extra_end_rules`404 parameter is forwarded to the tuple parsing function.404 parameter is forwarded to the tuple parsing function. If405 `with_namespace` is enabled, a namespace assignment may be parsed.406 """406 if name_only:407 if with_namespace and self.stream.look().type == 'dot':408 token = self.stream.expect('name')409 next(self.stream) # dot410 attr = self.stream.expect('name')411 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)412 elif name_only:413 token = self.stream.expect('name')414 target = nodes.Name(token.value, 'store', lineno=token.lineno)415 else:416 if with_tuple:417 target = self.parse_tuple(simplified=True,
487 unmodified lines
modified:jinja2/runtime.py+2 added-2 removed
13 unmodified lines
14from types import MethodType1516from jinja2.nodes import EvalContext, _context_function_types17from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \18 internalcode, object_type_repr, evalcontextfunction18 internalcode, object_type_repr, evalcontextfunction, Namespace19from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \20 TemplateNotFound21from jinja2._compat import imap, text_type, iteritems, \22 implements_iterator, implements_to_string, string_types, PY2, \
3 unmodified lines
26# these variables are exported to the template runtime27__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',28 'TemplateRuntimeError', 'missing', 'concat', 'escape',29 'markup_join', 'unicode_join', 'to_string', 'identity',30 'TemplateNotFound']30 'TemplateNotFound', 'Namespace']3132#: the name of the function that is used to convert something into33#: a string. We can just use the text type here.34to_string = text_type
778 unmodified lines
modified:jinja2/utils.py+23 added
610 unmodified lines
611 return u''612 return self.sep613614615class Namespace(object):616 """A namespace object that can hold arbitrary attributes. It may be617 initialized from a dictionary or with keyword argments."""618619 def __init__(*args, **kwargs):620 self, args = args[0], args[1:]621 self.__attrs = dict(*args, **kwargs)622623 def __getattribute__(self, name):624 if name == '_Namespace__attrs':625 return object.__getattribute__(self, name)626 try:627 return self.__attrs[name]628 except KeyError:629 raise AttributeError(name)630631 def __setitem__(self, name, value):632 self.__attrs[name] = value633634 def __repr__(self):635 return '<Namespace %r>' % self.__attrs636637638# does this python version support async for in and async generators?639try:640 exec('async def _():\n async for _ in ():\n yield _')641 have_async_gen = True
6 unmodified lines
modified:tests/test_core_tags.py+55 added-2 removed
7 unmodified lines
8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import pytest12from jinja2 import Environment, TemplateSyntaxError, UndefinedError, \13 DictLoader12from jinja2 import Environment, TemplateSyntaxError, TemplateRuntimeError, \13 UndefinedError, DictLoader141516@pytest.fixture17def env_trim():
372 unmodified lines
390 tmpl = env.from_string('{% set foo %}<em>{{ test }}</em>'391 '{% endset %}foo: {{ foo }}')392 assert tmpl.render(test='<unsafe>') == 'foo: <em>&lt;unsafe&gt;</em>'393394 def test_set_invalid(self, env_trim):395 pytest.raises(TemplateSyntaxError, env_trim.from_string,396 "{% set foo['bar'] = 1 %}")397 tmpl = env_trim.from_string('{% set foo.bar = 1 %}')398 exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, foo={})399 assert 'non-namespace object' in exc_info.value.message400401 def test_namespace_redefined(self, env_trim):402 tmpl = env_trim.from_string('{% set ns = namespace() %}'403 '{% set ns.bar = "hi" %}')404 exc_info = pytest.raises(TemplateRuntimeError, tmpl.render,405 namespace=dict)406 assert 'non-namespace object' in exc_info.value.message407408 def test_namespace(self, env_trim):409 tmpl = env_trim.from_string('{% set ns = namespace() %}'410 '{% set ns.bar = "42" %}'411 '{{ ns.bar }}')412 assert tmpl.render() == '42'413414 def test_namespace_block(self, env_trim):415 tmpl = env_trim.from_string('{% set ns = namespace() %}'416 '{% set ns.bar %}42{% endset %}'417 '{{ ns.bar }}')418 assert tmpl.render() == '42'419420 def test_init_namespace(self, env_trim):421 tmpl = env_trim.from_string('{% set ns = namespace(d, self=37) %}'422 '{% set ns.b = 42 %}'423 '{{ ns.a }}|{{ ns.self }}|{{ ns.b }}')424 assert tmpl.render(d={'a': 13}) == '13|37|42'425426 def test_namespace_loop(self, env_trim):427 tmpl = env_trim.from_string('{% set ns = namespace(found=false) %}'428 '{% for x in range(4) %}'429 '{% if x == v %}'430 '{% set ns.found = true %}'431 '{% endif %}'432 '{% endfor %}'433 '{{ ns.found }}')434 assert tmpl.render(v=3) == 'True'435 assert tmpl.render(v=4) == 'False'436437 def test_namespace_macro(self, env_trim):438 tmpl = env_trim.from_string('{% set ns = namespace() %}'439 '{% set ns.a = 13 %}'440 '{% macro magic(x) %}'441 '{% set x.b = 37 %}'442 '{% endmacro %}'443 '{{ magic(ns) }}'444 '{{ ns.a }}|{{ ns.b }}')445 assert tmpl.render() == '13|37'446447448@pytest.mark.core_tags449@pytest.mark.with_450class TestWith(object):451
17 unmodified lines
modified:CHANGES+3 added
14 unmodified lines
15 undefined.16- Added `changed(*values)` to loop contexts, providing an easy way of checking17 whether a value has changed since the last iteration (or rather since the18 last call of the method)19- Added a `namespace` function that creates a special object which allows20 attribute assignment using the `set` tag. This can be used to carry data21 across scopes, e.g. from a loop body to code that comes after the loop.2223Version 2.9.624-------------25(bugfix release, released on April 3rd 2017)
504 unmodified lines