improved variable exporting, added TODO file
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 1de4c64 · Browse files · 6 files·+123 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+123 added−13 removed
- other:+123 added−13 removed
Provenance
- Commit
69e12db- Tree
916d709- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1de4c64
6 files changed+123 added−13 removed
modified:docs/jinjaext.py+6 added-3 removed
166 unmodified lines167 doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '')168 if node.abstract:169 members = []170 for key, name in node.__dict__.iteritems():171- if not key.startswith('_') and callable(name):171+ if not key.startswith('_') and \172+ not hasattr(node.__base__, key) and callable(name):173 members.append(key)174 if members:175 members.sort()176 doc.append('%s :members: %s' % (p, ', '.join(members)), '')176- else:177+ if node.__base__ != object:178 doc.append('', '')178- doc.append(p + ' :Node type: :class:`%s`' % node.__base__.__name__, '')179+ doc.append('%s :Node type: :class:`%s`' %180+ (p, node.__base__.__name__), '')181+ # XXX: sphinx bug? Expr gives a rst warning182 doc.append('', '')183 children = node.__subclasses__()184 children.sort(key=lambda x: x.__name__.lower())185 for child in children:10 unmodified linesmodified:docs/tricks.rst+2 added-2 removed
63 unmodified lines64 65 The layout template can then access `active_page`. Additionally it makes66 sense to defined a default for that variable::67 68- {% navigation_bar = [68+ {% set navigation_bar = [69 ('/', 'index', 'Index'),70 ('/downloads/', 'downloads', 'Downloads'),71 ('/about/', 'about', 'About')72 ] -%}73- {% active_page = active_page|default('index') -%}73+ {% set active_page = active_page|default('index') -%}74 ...75 <ul id="navigation">76 {% for href, id, caption in navigation_bar %}77 <li{% if id == active_page %} class="active"{% endif4 unmodified linesmodified:jinja2/compiler.py+19 added-3 removed
41 unmodified lines42 def generate(node, environment, name, filename, stream=None):43 """Generate the python source for a node tree."""44 if not isinstance(node, nodes.Template):45 raise TypeError('Can\'t compile non template nodes')46+ node.freeze()47 generator = CodeGenerator(environment, name, filename, stream)48 generator.visit(node)49 if stream is None:50 return generator.stream.getvalue()1087 unmodified lines1138 self.visit(node.node, frame)1139 1140 # make sure toplevel assignments are added to the context.1141 if frame.toplevel:1141- for name in assignment_frame.assigned_names:1142+ public_names = [x for x in assignment_frame.assigned_names1143+ if not x.startswith('__')]1144+ if len(assignment_frame.assigned_names) == 1:1145+ name = iter(assignment_frame.assigned_names).next()1146 self.writeline('context.vars[%r] = l_%s' % (name, name))1143- if not name.startswith('__'):1144- self.writeline('context.exported_vars.add(%r)' % name)1147+ else:1148+ self.writeline('context.vars.update({')1149+ for idx, name in enumerate(assignment_frame.assigned_names):1150+ if idx:1151+ self.write(', ')1152+ self.write('%r: l_%s' % (name, name))1153+ self.write('})')1154+ if public_names:1155+ if len(public_names) == 1:1156+ self.writeline('context.exported_vars.add(%r)' %1157+ public_names[0])1158+ else:1159+ self.writeline('context.exported_vars.update((%s))' %1160+ ', '.join(map(repr, public_names)))1161 1162 def visit_Name(self, node, frame):1163 if node.ctx == 'store' and frame.toplevel:1164 frame.assigned_names.add(node.name)189 unmodified linesmodified:jinja2/ext.py+5 added-5 removed
75 unmodified lines76 raise NotImplementedError()77 78 def attr(self, name, lineno=None):79 """Return an attribute node for the current extension. This is useful80- to pass callbacks to template code::80+ to pass constants on extensions to generated template code::81 82- nodes.Call(self.attr('_my_callback'), args, kwargs, None, None)83-84- That would call `self._my_callback` when the template is evaluated.82+ self.attr('_my_attribute', lineno=lineno)83 """84 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)85 86 def call_method(self, name, args=None, kwargs=None, dyn_args=None,87 dyn_kwargs=None, lineno=None):90- """Call a method of the extension."""88+ """Call a method of the extension. This is a shortcut for89+ :meth:`attr` + :class:`jinja2.nodes.Call`.90+ """91 if args is None:92 args = []93 if kwargs is None:94 kwargs = []269 unmodified linesmodified:jinja2/nodes.py+34 added
88 unmodified lines89 positional arguments, attributes as keyword arguments. Each node has90 two attributes: `lineno` (the line number of the node) and `environment`.91 The `environment` attribute is set at the end of the parsing process for92 all nodes automatically.93+94+ Nodes can be frozen which makes them hashable. The compiler freezes the95+ nodes automatically. Modifications on frozen nodes are possible but not96+ allowed.97 """98 __metaclass__ = NodeType99 fields = ()100 attributes = ('lineno', 'environment')101 abstract = True102+ frozen = False103 104 def __init__(self, *fields, **attributes):105+ if self.abstract:106+ raise TypeError('abstract nodes are not instanciable')107 if fields:108 if len(fields) != len(self.fields):109 if not self.fields:110 raise TypeError('%r takes 0 arguments' %108 unmodified lines219 node.environment = environment220 todo.extend(node.iter_child_nodes())221 return self222 223+ def freeze(self):224+ """Freeze the complete node tree which makes them hashable.225+ This happens automatically on compilation. Frozen nodes must not be226+ modified any further. Extensions may not freeze nodes that appear227+ in the final node tree (ie: nodes that are returned from the extension228+ parse method).229+ """230+ todo = deque([self])231+ while todo:232+ node = todo.popleft()233+ node.frozen = True234+ todo.extend(node.iter_child_nodes())235+236+ def __eq__(self, other):237+ return type(self) is type(other) and self.__dict__ == other.__dict__238+239+ def __ne__(self, other):240+ return not self.__eq__(other)241+242+ def __hash__(self):243+ if not self.frozen:244+ raise TypeError('unfrozen nodes are unhashable')245+ return hash(tuple(self.__dict__.items()))246+247 def __repr__(self):248 return '%s(%s)' % (249 self.__class__.__name__,250 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for153 unmodified lines404 class BinExpr(Expr):405 """Baseclass for all binary expressions."""406 fields = ('left', 'right')407 operator = None408+ abstract = True409 410 def as_const(self):411 f = _binop_to_func[self.operator]412 try:5 unmodified lines418 class UnaryExpr(Expr):419 """Baseclass for all unary expressions."""420 fields = ('node',)421 operator = None422+ abstract = True423 424 def as_const(self):425 f = _uaop_to_func[self.operator]426 try:17 unmodified lines444 445 446 class Literal(Expr):447 """Baseclass for literals."""448+ abstract = True449 450 451 class Const(Literal):452 """All constant values. The parser will return this node for simple351 unmodified linesadded:TODO+57 added
1+Todo Before Release2+===================3+4+This has to be implemented before the release:5+6+Drop special casing template globals7+------------------------------------8+9+The idea some time ago was to partially evaluate templates at compile time.10+For that we decided to not allow globals being overridden by locals as the11+static compiler could have changed semantics. Turns out that the static12+compiler blows up the complexity to something nobody wants to support which13+means that this restriction is kinda pointless.14+15+That should go for good.16+17+Pull Attributes Onces18+---------------------19+20+Imagine the following template::21+22+ {% if foo.bar %}23+ {{ baz(foo.bar) }}24+ {% endif %}25+26+Problem with that is that it compiles to this::27+28+ if environment.subscribe(l_foo, 'bar'):29+ if 0: yield None30+ yield u'\n %s\n' % (31+ l_baz(environment.subscribe(l_foo, 'bar')),32+ )33+34+As `environment.subscribe` is more expensive then regular attribute lookups35+(it tries getitem/getattr and in sandbox mode also permissions) multiple36+lookups with the same parameters in the same scope should get local aliases.37+The result we have is that one::38+39+ t1 = environment.subscribe(l_foo, 'bar')40+ if t1:41+ if 0: yield None42+ yield u'\n %s\n' % (43+ l_baz(t1),44+ )45+46+However that should only happen if the attribute is accessed multiple times47+unlike locals and filters/tests which are always pulled. We're not doing that48+for filters/tests/locals as nested scopes may access it and testing is too49+complicated for the tiny performance improvement but easy for attribute50+lookups, keeping the complexity of the whole thing in mind.51+52+Use `set` for Assignments53+-------------------------54+55+The keyword-less way to assign variabeles is a left-over from the days when56+it was possible to use Jinja2 like a regular programming language without57+necessary template end/start delimiters to group statements.