Improved attribute and item lookup by allowing template designers to express the priority. foo.bar checks foo.bar first and then foo['bar'] and the other way round.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent f3d3d7b · Browse files · 11 files·+131 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+131 added−35 removed
- tests:+6 added−5 removed
- other:+125 added−30 removed
Provenance
- Commit
6dc6f29- Tree
d9ee483- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f3d3d7b
11 files changed+131 added−35 removed
modified:docs/_static/style.css+4 added
225 unmodified lines226 font-weight: bold;227 font-size: 15px;228 }229 230+div.admonition p.admonition-title a {231+ color: white!important;232+}233+234 div.admonition-note {235 background: url(note.png) no-repeat 10px 40px;236 }237 152 unmodified linesmodified:docs/templates.rst+23 added
72 unmodified lines73 value. What you can do with that kind of value depends on the application74 configuration, the default behavior is that it evaluates to an empty string75 if printed and that you can iterate over it, but every other operation fails.76 77+.. _notes-on-subscribing:78+79+.. admonition:: Implementation80+81+ The process of looking up attributes and items of objects is called82+ "subscribing" an object. For convenience sake ``foo.bar`` in Jinja283+ does the following things on the Python layer:84+85+ - check if there is an attribute called `bar` on `foo`.86+ - if there is not, check if there is an item ``'bar'`` in `foo`.87+ - if there is not, return an undefined object.88+89+ ``foo['bar']`` on the other hand works mostly the same with the a small90+ difference in the order:91+92+ - check if there is an item ``'bar'`` in `foo`.93+ - if there is not, check if there is an attribute called `bar` on `foo`.94+ - if there is not, return an undefined object.95+96+ This is important if an object has an item or attribute with the same97+ name. Additionally there is the :func:`attr` filter that just looks up98+ attributes.99+100 .. _filters:101 102 Filters103 -------1008 unmodified linesmodified:jinja2/compiler.py+7 added-2 removed
1266 unmodified lines1267 def visit_Operand(self, node, frame):1268 self.write(' %s ' % operators[node.op])1269 self.visit(node.expr, frame)1270 1271- def visit_Subscript(self, node, frame):1271+ def visit_Getattr(self, node, frame):1272+ self.write('environment.getattr(')1273+ self.visit(node.node, frame)1274+ self.write(', %r)' % node.attr)1275+1276+ def visit_Getitem(self, node, frame):1277 # slices or integer subscriptions bypass the subscribe1278 # method if we can determine that at compile time.1279 if isinstance(node.arg, nodes.Slice) or \1280 (isinstance(node.arg, nodes.Const) and2 unmodified lines1283 self.write('[')1284 self.visit(node.arg, frame)1285 self.write(']')1286 else:1282- self.write('environment.subscribe(')1287+ self.write('environment.getitem(')1288 self.visit(node.node, frame)1289 self.write(', ')1290 self.visit(node.arg, frame)1291 self.write(')')99 unmodified linesmodified:jinja2/environment.py+15 added-2 removed
284 unmodified lines285 def lexer(self):286 """Return a fresh lexer for the environment."""287 return Lexer(self)288 289- def subscribe(self, obj, argument):290- """Get an item or attribute of an object."""289+ def getitem(self, obj, argument):290+ """Get an item or attribute of an object but prefer the item."""291 try:292 return obj[argument]293 except (TypeError, LookupError):294 if isinstance(argument, basestring):7 unmodified lines302 except AttributeError:303 pass304 return self.undefined(obj=obj, name=argument)305 306+ def getattr(self, obj, attribute):307+ """Get an item or attribute of an object but prefer the attribute.308+ Unlike :meth:`getitem` the attribute *must* be a bytestring.309+ """310+ try:311+ return getattr(obj, attribute)312+ except AttributeError:313+ pass314+ try:315+ return obj[attribute]316+ except (TypeError, LookupError):317+ return self.undefined(obj=obj, name=attribute)318+319 def parse(self, source, name=None, filename=None):320 """Parse the sourcecode and return the abstract syntax tree. This321 tree of nodes is used by the compiler to convert the template into322 executable source- or bytecode. This is useful for debugging or to379 unmodified linesmodified:jinja2/filters.py+6 added-9 removed
570 unmodified lines571 As you can see the item we're grouping by is stored in the `grouper`572 attribute and the `list` contains all the objects that have this grouper573 in common.574 """575- expr = lambda x: environment.subscribe(x, attribute)575+ expr = lambda x: environment.getitem(x, attribute)576 return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))577 578 579 class _GroupTuple(tuple):43 unmodified lines623 624 @environmentfilter625 def do_attr(environment, obj, name):626 """Get an attribute of an object. ``foo|attr("bar")`` works like627- ``foo["bar"]`` just that always an attribute is returned. This is useful628- if data structures are passed to the template that have an item that hides629- an attribute with the same name. For example a dict ``{'items': []}``630- that obviously hides the item method of a dict.627+ ``foo["bar"]`` just that always an attribute is returned and items are not628+ looked up.629+630+ See :ref:`Notes on subscribing <notes-on-subscribing>` for more details.631 """632 try:633 value = getattr(obj, name)634 except AttributeError:635 return environment.undefined(obj=obj, name=name)636 if environment.sandboxed and not \637 environment.is_safe_attribute(obj, name, value):638- return environment.undefined('access to attribute %r of %r '639- 'object is unsafe.' % (640- name, obj.__class__.__name__641- ), name=name, obj=obj, exc=SecurityError)638+ return environment.unsafe_undefined(obj, name)639 return value640 641 642 FILTERS = {46 unmodified linesmodified:jinja2/nodes.py+19 added-3 removed
580 unmodified lines581 except:582 raise Impossible()583 584 585-class Subscript(Expr):585+class Getitem(Expr):586 """Subscribe an expression by an argument. This node performs a dict587 and an attribute lookup on the object whatever succeeds.588 """589 fields = ('node', 'arg', 'ctx')1 unmodified line591 def as_const(self):592 if self.ctx != 'load':593 raise Impossible()594 try:595- return self.environment.subscribe(self.node.as_const(),596- self.arg.as_const())595+ return self.environment.getitem(self.node.as_const(),596+ self.arg.as_const())597 except:598 raise Impossible()599 600 def can_assign(self):601 return False602 603 604+class Getattr(Expr):605+ """Subscribe an attribute."""606+ fields = ('node', 'attr', 'ctx')607+608+ def as_const(self):609+ if self.ctx != 'load':610+ raise Impossible()611+ try:612+ return self.environment.getattr(self.node.as_const(), arg)613+ except:614+ raise Impossible()615+616+ def can_assign(self):617+ return False618+619+620 class Slice(Expr):621 """Represents a slice object. This must only be used as argument for622 :class:`Subscript`.623 """183 unmodified linesmodified:jinja2/optimizer.py+1 added-1 removed
61 unmodified lines62 return node63 64 visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \65 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \66- visit_Not = visit_Compare = visit_Subscript = visit_Call = \66+ visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \67 visit_Filter = visit_Test = visit_CondExpr = fold68 del foldmodified:jinja2/parser.py+10 added-6 removed
563 unmodified lines564 def parse_subscript(self, node):565 token = self.stream.next()566 if token.type is 'dot':567 attr_token = self.stream.current568- if attr_token.type not in ('name', 'integer'):568+ self.stream.next()569+ if attr_token.type is 'name':570+ return nodes.Getattr(node, attr_token.value, 'load',571+ lineno=token.lineno)572+ elif attr_token.type is not 'integer':573 self.fail('expected name or number', attr_token.lineno)574 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)571- self.stream.next()572- elif token.type is 'lbracket':575+ return nodes.Getitem(node, arg, 'load', lineno=token.lineno)576+ if token.type is 'lbracket':577+ priority_on_attribute = False578 args = []579 while self.stream.current.type is not 'rbracket':580 if args:581 self.stream.expect('comma')2 unmodified lines584 if len(args) == 1:585 arg = args[0]586 else:587 arg = nodes.Tuple(args, self.lineno, self.filename)583- else:584- self.fail('expected subscript expression', self.lineno)585- return nodes.Subscript(node, arg, 'load', lineno=token.lineno)588+ return nodes.Getitem(node, arg, 'load', lineno=token.lineno)589+ self.fail('expected subscript expression', self.lineno)590 591 def parse_subscribed(self):592 lineno = self.stream.current.lineno593 167 unmodified linesmodified:jinja2/sandbox.py+27 added-6 removed
181 unmodified lines182 """183 return not (getattr(obj, 'unsafe_callable', False) or \184 getattr(obj, 'alters_data', False))185 186- def subscribe(self, obj, argument):186+ def getitem(self, obj, argument):187 """Subscribe an object from sandboxed code."""188 try:189 return obj[argument]190 except (TypeError, LookupError):9 unmodified lines200 pass201 else:202 if self.is_safe_attribute(obj, argument, value):203 return value204- return self.undefined('access to attribute %r of %r '205- 'object is unsafe.' % (206- argument,207- obj.__class__.__name__208- ), name=argument, obj=obj, exc=SecurityError)204+ return self.unsafe_undefined(obj, argument)205 return self.undefined(obj=obj, name=argument)206 207+ def getattr(self, obj, attribute):208+ """Subscribe an object from sandboxed code and prefer the209+ attribute. The attribute passed *must* be a bytestring.210+ """211+ try:212+ value = getattr(obj, attribute)213+ except AttributeError:214+ try:215+ return obj[argument]216+ except (TypeError, LookupError):217+ pass218+ else:219+ if self.is_safe_attribute(obj, attribute, value):220+ return value221+ return self.unsafe_undefined(obj, attribute)222+ return self.undefined(obj=obj, name=argument)223+224+ def unsafe_undefined(self, obj, attribute):225+ """Return an undefined object for unsafe attributes."""226+ return self.undefined('access to attribute %r of %r '227+ 'object is unsafe.' % (228+ attribute,229+ obj.__class__.__name__230+ ), name=attribute, obj=obj, exc=SecurityError)231+232 def call(__self, __context, __obj, *args, **kwargs):233 """Call an object from sandboxed code."""234 # the double prefixes are to avoid double keyword argument235 # errors when proxying the call.15 unmodified linesmodified:tests/test_various.py+6 added-5 removed
58 unmodified lines59 counts.add(len(gc.get_objects()))60 assert len(counts) == 1, 'ouch, c extension seems to leak objects'61 62 63-def test_item_before_attribute():63+def test_item_and_attribute():64 from jinja2 import Environment65 from jinja2.sandbox import SandboxedEnvironment66 67 for env in Environment(), SandboxedEnvironment():68 tmpl = env.from_string('{{ foo.items() }}')69- assert tmpl.render(foo={'items': lambda: 42}) == '42'70- assert tmpl.render(foo={}) == '[]'71- tmpl = env.from_string('{{ foo|attr("items")() }}')72- assert tmpl.render(foo={'items': None}) == "[('items', None)]"69+ assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"70+ tmpl = env.from_string('{{ foo|attr("items") }}')71+ assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"72+ tmpl = env.from_string('{{ foo["items"] }}')73+ assert tmpl.render(foo={'items': 42}) == '42'modified:CHANGES+13 added-1 removed
3 unmodified lines4 Version 2.05 -----------6 (codename to be selected, release around July 2008)7 8+- the subscribing of objects (looking up attributes and items) changed from9+ slightly. It's now possible to give attributes or items a higher priority10+ by either using dot-notation lookup or the bracket syntax. This also11+ changed the AST slightly. `Subscript` is gone and was replaced with12+ :class:`~jinja2.nodes.Getitem` and :class:`~jinja2.nodes.Getattr`.13+14+ For more information see :ref:`the implementation details <notes-on-subscribing>`.15+16+Version 2.0rc117+--------------18+(no codename, released on July 9th 2008)19+8-- initial release of Jinja220+- first release of Jinja2