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
Provenance
- Commit
c7dfa21- Tree
675b802- Author
Adrian <adrian@planetcoding.net>- Committer
GitHub <noreply@github.com>- Parent 1
b73cb48- Parent 2
e0475f9
12 files changed+168 added−11 removed
modified:docs/api.rst+2 added
685 unmodified lines686 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.689 690+.. autoexception:: jinja2.TemplateRuntimeError691+692 .. autoexception:: jinja2.TemplateAssertionError693 694 695 .. _writing-filters:230 unmodified linesmodified:docs/templates.rst+41 added
906 unmodified lines907 {% else %}908 did not iterate909 {% endfor %}910 911+ As of version 2.10 more complex use cases can be handled using namespace912+ objects which allow propagating of changes across scopes::913 914+ {% 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 }}922+923+ 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.926+927+ .. versionadded:: 2.10 Added support for namespace objects928+929+930 Block Assignments931 ~~~~~~~~~~~~~~~~~932 933 .. versionadded:: 2.8483 unmodified lines1417 {% endif %}1418 1419 .. versionadded:: 2.11420 1421+.. class:: namespace(...)1422 1423+ Creates a new container that allows attribute assignment using the1424+ ``{% set %}`` tag::1425+1426+ {% set ns = namespace() %}1427+ {% set ns.foo = 'bar' %}1428+1429+ 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)::1432+1433+ {% 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 }}1441+1442+ .. versionadded:: 2.101443+1444+1445 Extensions1446 ----------1447 1448 The following sections cover the built-in Jinja2 extensions that may be192 unmodified linesmodified:jinja2/__init__.py+2 added-1 removed
46 unmodified lines47 48 # exceptions49 from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \51- TemplateAssertionError51+ TemplateAssertionError, TemplateRuntimeError52 53 # decorators and public utilities54 from jinja2.filters import environmentfilter, contextfilter, \55 evalcontextfilter7 unmodified lines63 '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 linesmodified:jinja2/compiler.py+12 added
1401 unmodified lines1402 return1403 1404 self.write(ref)1405 1406+ 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))1417+1418 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 linesmodified:jinja2/defaults.py+3 added-2 removed
7 unmodified lines8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 from jinja2._compat import range_type12-from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner12+from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner, Namespace13 14 15 # defaults for the parser / lexer16 BLOCK_START_STRING = '{%'17 unmodified lines34 'range': range_type,35 'dict': dict,36 'lipsum': generate_lorem_ipsum,37 'cycler': Cycler,38- 'joiner': Joiner38+ 'joiner': Joiner,39+ 'namespace': Namespace40 }41 42 43 # default policies12 unmodified linesmodified:jinja2/idtracking.py+3 added
213 unmodified lines214 self.symbols.store(node.name)215 elif node.ctx == 'load':216 self.symbols.load(node.name)217 218+ def visit_NSRef(self, node, **kwargs):219+ self.symbols.load(node.name)220+221 def visit_If(self, node, **kwargs):222 self.visit(node.test, **kwargs)223 224 original_symbols = self.symbols61 unmodified linesmodified:jinja2/nodes.py+12 added
463 unmodified lines464 return self.name not in ('true', 'false', 'none',465 'True', 'False', 'None')466 467 468+class NSRef(Expr):469+ """Reference to a namespace value assignment"""470+ fields = ('name', 'attr')471+472+ 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 True478+479+480 class Literal(Expr):481 """Baseclass for literals."""482 abstract = True483 484 unmodified linesmodified:jinja2/parser.py+10 added-4 removed
174 unmodified lines175 176 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 lines394 node.nodes.append(self.parse_expression())395 return node396 397 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 linesmodified:jinja2/runtime.py+2 added-2 removed
13 unmodified lines14 from types import MethodType15 16 from jinja2.nodes import EvalContext, _context_function_types17 from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \18- internalcode, object_type_repr, evalcontextfunction18+ internalcode, object_type_repr, evalcontextfunction, Namespace19 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \20 TemplateNotFound21 from jinja2._compat import imap, text_type, iteritems, \22 implements_iterator, implements_to_string, string_types, PY2, \3 unmodified lines26 # 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']31 32 #: the name of the function that is used to convert something into33 #: a string. We can just use the text type here.34 to_string = text_type778 unmodified linesmodified:jinja2/utils.py+23 added
610 unmodified lines611 return u''612 return self.sep613 614 615+class Namespace(object):616+ """A namespace object that can hold arbitrary attributes. It may be617+ initialized from a dictionary or with keyword argments."""618+619+ def __init__(*args, **kwargs):620+ self, args = args[0], args[1:]621+ self.__attrs = dict(*args, **kwargs)622+623+ 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)630+631+ def __setitem__(self, name, value):632+ self.__attrs[name] = value633+634+ def __repr__(self):635+ return '<Namespace %r>' % self.__attrs636+637+638 # does this python version support async for in and async generators?639 try:640 exec('async def _():\n async for _ in ():\n yield _')641 have_async_gen = True6 unmodified linesmodified:tests/test_core_tags.py+55 added-2 removed
7 unmodified lines8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import pytest12-from jinja2 import Environment, TemplateSyntaxError, UndefinedError, \13- DictLoader12+from jinja2 import Environment, TemplateSyntaxError, TemplateRuntimeError, \13+ UndefinedError, DictLoader14 15 16 @pytest.fixture17 def env_trim():372 unmodified lines390 tmpl = env.from_string('{% set foo %}<em>{{ test }}</em>'391 '{% endset %}foo: {{ foo }}')392 assert tmpl.render(test='<unsafe>') == 'foo: <em><unsafe></em>'393 394+ 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.message400 401+ 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.message407+408+ 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'413+414+ 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'419+420+ 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'425+426+ 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'436+437+ 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'446+447+448 @pytest.mark.core_tags449 @pytest.mark.with_450 class TestWith(object):451 17 unmodified linesmodified:CHANGES+3 added
14 unmodified lines15 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.22 23 Version 2.9.624 -------------25 (bugfix release, released on April 3rd 2017)504 unmodified lines