Skip to content
Myr

removed unused imports

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 2e30cf5 · Browse files · 5 files+30 added−178 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+30 added−178 removed

  • other:+30 added−178 removed

5 files+30 added−178 removed

modified:docs/api.rst+7 added-7 removed
79 unmodified lines
8081 .. attribute:: globals8283 A dict of global variables. These variables are always available84 in a template and (if the optimizer is enabled) may not be85 overridden by templates. As long as no template was loaded it's safe84 in a template. As long as no template was loaded it's safe85 to modify this dict. For more details see :ref:`global-namespace`.86 For valid object names have a look at :ref:`identifier-naming`.8788 .. automethod:: overlay([options])
273 unmodified lines
362363The Global Namespace364--------------------365367Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`368dicts are special as they are available for imported templates too and will be369used by the optimizer in future releases to evaluates parts of the template at370compile time. This is the place where you can put variables and functions371that should be available all the time.366Variables stored in the :attr:`Environment.globals` dict are special as they367are available for imported templates too, even if they are imported without368context. This is the place where you can put variables and functions369that should be available all the time. Additionally :attr:`Template.globals`370exist that are variables available to a specific template that are available371to all :meth:`~Template.render` calls.
modified:jinja2/environment.py+12 added-32 removed
308 unmodified lines
309 and debugging templates.310 """311 return self.lexer.tokeniter(source, filename)312313 def compile(self, source, name=None, filename=None, globals=None,314 raw=False):313 def compile(self, source, name=None, filename=None, raw=False):314 """Compile a node or template source code. The `name` parameter is315 the load name of the template after it was joined using316 :meth:`join_path` if necessary, not the filename on the file system.317 the `filename` parameter is the estimated filename of the template on318 the file system. If the template came from a database or memory this320 can be omitted. The `globals` parameter can be used to provide extra321 variables at compile time for the template. In the future the322 optimizer will be able to evaluate parts of the template at compile323 time based on those variables.319 can be omitted.320321 The return value of this method is a python code object. If the `raw`322 parameter is `True` the return value will be a string with python323 code equivalent to the bytecode returned otherwise. This method is
1 unmodified line
325 """326 if isinstance(source, basestring):327 source = self.parse(source, filename)328 if self.optimized:333 node = optimize(source, self, globals or {})329 node = optimize(source, self)330 source = generate(node, self, name, filename)331 if raw:332 return source333 if filename is None:
19 unmodified lines
353 method ask the loader for the template and returns a :class:`Template`.354 If the `parent` parameter is not `None`, :meth:`join_path` is called355 to get the real template name before loading.356361 The `globals` parameter can be used to provide compile-time globals.362 In the future this will allow the optimizer to render parts of the363 templates at compile-time.357 The `globals` parameter can be used to provide temlate wide globals.358 These variables are available in the context at render time.359360 If the template does not exist a :exc:`TemplateNotFound` exception is361 raised.362 """
18 unmodified lines
381 returns a :class:`Template` object.382 """383 globals = self.make_globals(globals)384 cls = template_class or self.template_class390 return cls.from_code(self, self.compile(source, globals=globals),391 globals, None)385 return cls.from_code(self, self.compile(source), globals, None)386387 def make_globals(self, d):388 """Return a dict for the globals."""389 if d is None:
116 unmodified lines
506 exc_type, exc_value, tb = translate_exception(sys.exc_info())507 raise exc_type, exc_value, tb508509 def _generate(self, *args, **kwargs):516 # assemble the context517 context = dict(*args, **kwargs)510 """Creates a new context and generates the template."""511 return self.root_render_func(self.new_context(dict(*args, **kwargs)))512519 # if the environment is using the optimizer locals may never520 # override globals as optimizations might have happened521 # depending on values of certain globals. This assertion goes522 # away if the python interpreter is started with -O523 if __debug__ and self.environment.optimized:524 overrides = set(context) & set(self.globals)525 if overrides:526 plural = len(overrides) != 1 and 's' or ''527 raise AssertionError('the per template variable%s %s '528 'override%s global variable%s. '529 'With an enabled optimizer this '530 'will lead to unexpected results.' %531 (plural, ', '.join(overrides), plural or ' a', plural))532533 return self.root_render_func(self.new_context(context))534513 def new_context(self, vars=None, shared=False):514 """Create a new template context for this template. The vars515 provided will be passed to the template. Per default the globals516 are added to the context, if shared is set to `True` the data
128 unmodified lines
645646 while 1:647 try:648 while c_size < size:671 push(next())672 c_size += 1649 c = next()650 push(c)651 if c:652 c_size += 1653 except StopIteration:654 if not c_size:655 return656 yield concat(buf)
16 unmodified lines
modified:jinja2/loaders.py+1 added-1 removed
84 unmodified lines
85 """86 if globals is None:87 globals = {}88 source, filename, uptodate = self.get_source(environment, name)89 code = environment.compile(source, name, filename, globals)89 code = environment.compile(source, name, filename)90 return environment.template_class.from_code(environment, code,91 globals, uptodate)9293
180 unmodified lines
modified:jinja2/optimizer.py+10 added-127 removed
15 unmodified lines
16 :copyright: Copyright 2008 by Christoph Hack, Armin Ronacher.17 :license: GNU GPL.18"""19from jinja2 import nodes20from jinja2.visitor import NodeVisitor, NodeTransformer21from jinja2.runtime import LoopContext22from jinja2.utils import concat20from jinja2.visitor import NodeTransformer212225def optimize(node, environment, context_hint=None):23def optimize(node, environment):24 """The context hint can be used to perform an static optimization25 based on the context given."""26 optimizer = Optimizer(environment)29 return optimizer.visit(node, ContextStack(context_hint))27 return optimizer.visit(node)282932class ContextStack(object):33 """Simple compile time context implementation."""34 undefined = object()3536 def __init__(self, initial=None):37 self.stack = [{}]38 if initial is not None:39 self.stack.insert(0, initial)4041 def push(self):42 self.stack.append({})4344 def pop(self):45 self.stack.pop()4647 def get(self, key, default=None):48 try:49 return self[key]50 except KeyError:51 return default5253 def undef(self, name):54 if name in self:55 self[name] = self.undefined5657 def __contains__(self, key):58 try:59 self[key]60 except KeyError:61 return False62 return True6364 def __getitem__(self, key):65 for level in reversed(self.stack):66 if key in level:67 rv = level[key]68 if rv is self.undefined:69 raise KeyError(key)70 return rv71 raise KeyError(key)7273 def __setitem__(self, key, value):74 self.stack[-1][key] = value7576 def blank(self):77 """Return a new context with nothing but the root scope."""78 return ContextStack(self.stack[0])798030class Optimizer(NodeTransformer):3132 def __init__(self, environment):33 self.environment = environment3486 def visit_Block(self, node, context):87 block_context = context.blank()88 for name in 'super', 'self':89 block_context.undef(name)90 return self.generic_visit(node, block_context)9192 def visit_For(self, node, context):93 context.push()94 context.undef('loop')35 def visit_If(self, node):36 """Eliminate dead code."""37 try:96 return self.generic_visit(node, context)97 finally:98 context.pop()99100 def visit_Macro(self, node, context):101 context.push()102 for name in 'varargs', 'kwargs', 'caller':103 context.undef(name)104 try:105 return self.generic_visit(node, context)106 finally:107 context.pop()108109 def visit_CallBlock(self, node, context):110 context.push()111 for name in 'varargs', 'kwargs':112 context.undef(name)113 try:114 return self.generic_visit(node, context)115 finally:116 context.pop()117118 def visit_FilterBlock(self, node, context):119 """Try to filter a block at compile time."""120 context.push()121 try:122 return self.generic_visit(node, context)123 finally:124 context.pop()125126 def visit_If(self, node, context):127 try:128 val = self.visit(node.test, context).as_const()38 val = self.visit(node.test).as_const()39 except nodes.Impossible:130 return self.generic_visit(node, context)40 return self.generic_visit(node)41 if val:42 body = node.body43 else:44 body = node.else_45 result = []46 for node in body:137 result.extend(self.visit_list(node, context))47 result.extend(self.visit_list(node))48 return result49140 def visit_Name(self, node, context):141 if node.ctx != 'load':142 # something overwrote the variable, we can no longer use143 # the constant from the context144 context.undef(node.name)145 return node146 try:147 return nodes.Const.from_untrusted(context[node.name],148 lineno=node.lineno,149 environment=self.environment)150 except (KeyError, nodes.Impossible):151 return node152153 def visit_Import(self, node, context):154 rv = self.generic_visit(node, context)155 context.undef(node.target)156 return rv157158 def visit_FromImport(self, node, context):159 rv = self.generic_visit(node, context)160 for name in node.names:161 if isinstance(name, tuple):162 context.undef(name[1])163 else:164 context.undef(name)165 return rv166167 def fold(self, node, context):50 def fold(self, node):51 """Do constant folding."""169 node = self.generic_visit(node, context)52 node = self.generic_visit(node)53 try:54 return nodes.Const.from_untrusted(node.as_const(),55 lineno=node.lineno,56 environment=self.environment)
8 unmodified lines
modified:TODO-11 removed
1 unmodified line
2===================34This has to be implemented before the release:56Drop special casing template globals7------------------------------------89The idea some time ago was to partially evaluate templates at compile time.10For that we decided to not allow globals being overridden by locals as the11static compiler could have changed semantics. Turns out that the static12compiler blows up the complexity to something nobody wants to support which13means that this restriction is kinda pointless.1415That should go for good.166Pull Attributes Onces7---------------------89Imagine the following template::
30 unmodified lines