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
Provenance
- Commit
981cbf6- Tree
930ca8b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2e30cf5
5 files changed+30 added−178 removed
modified:docs/api.rst+7 added-7 removed
79 unmodified lines80 81 .. attribute:: globals82 83 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`.87 88 .. automethod:: overlay([options])273 unmodified lines362 363 The Global Namespace364 --------------------365 367-Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`368-dicts are special as they are available for imported templates too and will be369-used by the optimizer in future releases to evaluates parts of the template at370-compile time. This is the place where you can put variables and functions371-that should be available all the time.366+Variables stored in the :attr:`Environment.globals` dict are special as they367+are available for imported templates too, even if they are imported without368+context. This is the place where you can put variables and functions369+that should be available all the time. Additionally :attr:`Template.globals`370+exist that are variables available to a specific template that are available371+to all :meth:`~Template.render` calls.modified:jinja2/environment.py+12 added-32 removed
308 unmodified lines309 and debugging templates.310 """311 return self.lexer.tokeniter(source, filename)312 313- 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.320 321 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 is1 unmodified line325 """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 lines353 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.356 361- 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.359 360 If the template does not exist a :exc:`TemplateNotFound` exception is361 raised.362 """18 unmodified lines381 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)386 387 def make_globals(self, d):388 """Return a dict for the globals."""389 if d is None:116 unmodified lines506 exc_type, exc_value, tb = translate_exception(sys.exc_info())507 raise exc_type, exc_value, tb508 509 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)))512 519- # 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))532-533- return self.root_render_func(self.new_context(context))534-513 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 data128 unmodified lines645 646 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 linesmodified:jinja2/loaders.py+1 added-1 removed
84 unmodified lines85 """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)92 93 180 unmodified linesmodified:jinja2/optimizer.py+10 added-127 removed
15 unmodified lines16 :copyright: Copyright 2008 by Christoph Hack, Armin Ronacher.17 :license: GNU GPL.18 """19 from jinja2 import nodes20-from jinja2.visitor import NodeVisitor, NodeTransformer21-from jinja2.runtime import LoopContext22-from jinja2.utils import concat20+from jinja2.visitor import NodeTransformer21 22 25-def optimize(node, environment, context_hint=None):23+def 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)28 29 32-class ContextStack(object):33- """Simple compile time context implementation."""34- undefined = object()35-36- def __init__(self, initial=None):37- self.stack = [{}]38- if initial is not None:39- self.stack.insert(0, initial)40-41- def push(self):42- self.stack.append({})43-44- def pop(self):45- self.stack.pop()46-47- def get(self, key, default=None):48- try:49- return self[key]50- except KeyError:51- return default52-53- def undef(self, name):54- if name in self:55- self[name] = self.undefined56-57- def __contains__(self, key):58- try:59- self[key]60- except KeyError:61- return False62- return True63-64- 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)72-73- def __setitem__(self, key, value):74- self.stack[-1][key] = value75-76- def blank(self):77- """Return a new context with nothing but the root scope."""78- return ContextStack(self.stack[0])79-80-30 class Optimizer(NodeTransformer):31 32 def __init__(self, environment):33 self.environment = environment34 86- 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)91-92- 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()99-100- 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()108-109- 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()117-118- 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()125-126- 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 result49 140- 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 node152-153- def visit_Import(self, node, context):154- rv = self.generic_visit(node, context)155- context.undef(node.target)156- return rv157-158- 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 rv166-167- 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 linesmodified:TODO-11 removed
1 unmodified line2 ===================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-6 Pull Attributes Onces7 ---------------------8 9 Imagine the following template::30 unmodified lines