desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Parse an assign statement.'
def parse_set(self):
lineno = next(self.stream).lineno target = self.parse_assign_target() self.stream.expect('assign') expr = self.parse_tuple() return nodes.Assign(target, expr, lineno=lineno)
'Parse a for loop.'
def parse_for(self):
lineno = self.stream.expect('name:for').lineno target = self.parse_assign_target(extra_end_rules=('name:in',)) self.stream.expect('name:in') iter = self.parse_tuple(with_condexpr=False, extra_end_rules=('name:recursive',)) test = None if self.stream.skip_if('name:if'): test = self.parse_...
'Parse an if construct.'
def parse_if(self):
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', 'name:endif')) token = next(self.stream) if token.test('name:elif'): new_node ...
'Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `ex...
def parse_assign_target(self, with_tuple=True, name_only=False, extra_end_rules=None):
if name_only: token = self.stream.expect('name') target = nodes.Name(token.value, 'store', lineno=token.lineno) else: if with_tuple: target = self.parse_tuple(simplified=True, extra_end_rules=extra_end_rules) else: target = self.parse_primary() tar...
'Parse an expression. Per default all expressions are parsed, if the optional `with_condexpr` parameter is set to `False` conditional expressions are not parsed.'
def parse_expression(self, with_condexpr=True):
if with_condexpr: return self.parse_condexpr() return self.parse_or()
'Works like `parse_expression` but if multiple expressions are delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created. This method could also return a regular expression instead of a tuple if no commas where found. The default parsing mode is a full tuple. If `simplified` is `True` only names and literals...
def parse_tuple(self, simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False):
lineno = self.stream.current.lineno if simplified: parse = self.parse_primary elif with_condexpr: parse = self.parse_expression else: parse = (lambda : self.parse_expression(with_condexpr=False)) args = [] is_tuple = False while 1: if args: self.st...
'Parse the whole template into a `Template` node.'
def parse(self):
result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
'Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead.'
def get_visitor(self, node):
method = ('visit_' + node.__class__.__name__) return getattr(self, method, None)
'Visit a node.'
def visit(self, node, *args, **kwargs):
f = self.get_visitor(node) if (f is not None): return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
'Called if no explicit visitor function exists for a node.'
def generic_visit(self, node, *args, **kwargs):
for node in node.iter_child_nodes(): self.visit(node, *args, **kwargs)
'As transformers may return lists in some places this method can be used to enforce a list as return value.'
def visit_list(self, node, *args, **kwargs):
rv = self.visit(node, *args, **kwargs) if (not isinstance(rv, list)): rv = [rv] return rv
'Called during template compilation with the name of a unary operator to check if it should be intercepted at runtime. If this method returns `True`, :meth:`call_unop` is excuted for this unary operator. The default implementation of :meth:`call_unop` will use the :attr:`unop_table` dictionary to perform the operator...
def intercept_unop(self, operator):
return False
'The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the :func:`is_internal_attribute` function.'
def is_safe_attribute(self, obj, attr, value):
return (not (attr.startswith('_') or is_internal_attribute(obj, attr)))
'Check if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won\'t affect the `unsafe` decorator from this module.'
def is_safe_callable(self, obj):
return (not (getattr(obj, 'unsafe_callable', False) or getattr(obj, 'alters_data', False)))
'For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6'
def call_binop(self, context, operator, left, right):
return self.binop_table[operator](left, right)
'For intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6'
def call_unop(self, context, operator, arg):
return self.unop_table[operator](arg)
'Subscribe an object from sandboxed code.'
def getitem(self, obj, argument):
try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, basestring): try: attr = str(argument) except Exception: pass else: try: value = getattr(obj, attr) ...
'Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring.'
def getattr(self, obj, attribute):
try: value = getattr(obj, attribute) except AttributeError: try: return obj[attribute] except (TypeError, LookupError): pass else: if self.is_safe_attribute(obj, attribute, value): return value return self.unsafe_undefined(obj, attr...
'Return an undefined object for unsafe attributes.'
def unsafe_undefined(self, obj, attribute):
return self.undefined(('access to attribute %r of %r object is unsafe.' % (attribute, obj.__class__.__name__)), name=attribute, obj=obj, exc=SecurityError)
'Call an object from sandboxed code.'
def call(__self, __context, __obj, *args, **kwargs):
if (not __self.is_safe_callable(__obj)): raise SecurityError(('%r is not safely callable' % (__obj,))) return __context.call(__obj, *args, **kwargs)
'Resets the bucket (unloads the bytecode).'
def reset(self):
self.code = None
'Loads bytecode from a file or file like object.'
def load_bytecode(self, f):
magic = f.read(len(bc_magic)) if (magic != bc_magic): self.reset() return checksum = pickle.load(f) if (self.checksum != checksum): self.reset() return self.code = marshal_load(f)
'Dump the bytecode into the file or file like object passed.'
def write_bytecode(self, f):
if (self.code is None): raise TypeError("can't write empty bucket") f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal_dump(self.code, f)
'Load bytecode from a string.'
def bytecode_from_string(self, string):
self.load_bytecode(BytesIO(string))
'Return the bytecode as string.'
def bytecode_to_string(self):
out = BytesIO() self.write_bytecode(out) return out.getvalue()
'Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.'
def load_bytecode(self, bucket):
raise NotImplementedError()
'Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.'
def dump_bytecode(self, bucket):
raise NotImplementedError()
'Returns the unique hash key for this template name.'
def get_cache_key(self, name, filename=None):
hash = sha1(name.encode('utf-8')) if (filename is not None): filename = ('|' + filename) if isinstance(filename, unicode): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
'Returns a checksum for the source.'
def get_source_checksum(self, source):
return sha1(source.encode('utf-8')).hexdigest()
'Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.'
def get_bucket(self, environment, name, filename, source):
key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
'Put the bucket into the cache.'
def set_bucket(self, bucket):
self.dump_bytecode(bucket)
'Get the template source, filename and reload helper for a template. It\'s passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can\'t locate the template. The source part of the returned tuple must be the source of the...
def get_source(self, environment, template):
if (not self.has_source_access): raise RuntimeError(('%s cannot provide access to the source' % self.__class__.__name__)) raise TemplateNotFound(template)
'Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.'
def list_templates(self):
raise TypeError('this loader cannot iterate over all templates')
'Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.'
@internalcode def load(self, environment, name, globals=None):
code = None if (globals is None): globals = {} (source, filename, uptodate) = self.get_source(environment, name) bcc = environment.bytecode_cache if (bcc is not None): bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code if (code is None): ...
'Adds an extension after the environment was created. .. versionadded:: 2.5'
def add_extension(self, extension):
self.extensions.update(load_extensions(self, [extension]))
'Add the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions <writing-extensions>` to register callbacks and configuration values without breaking inheritance.'
def extend(self, **attributes):
for (key, value) in attributes.iteritems(): if (not hasattr(self, key)): setattr(self, key, value)
'Create a new overlay environment that shares all the data with the current environment except of cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensi...
def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, extensions=missing, optimized=missing, undefined=...
args = dict(locals()) del args['self'], args['cache_size'], args['extensions'] rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.overlayed = True rv.linked_to = self for (key, value) in args.iteritems(): if (value is not missing): setattr(rv, key, v...
'Iterates over the extensions by priority.'
def iter_extensions(self):
return iter(sorted(self.extensions.values(), key=(lambda x: x.priority)))
'Get an item or attribute of an object but prefer the item.'
def getitem(self, obj, argument):
try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, basestring): try: attr = str(argument) except Exception: pass else: try: return getattr(obj, attr) ...
'Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring.'
def getattr(self, obj, attribute):
try: return getattr(obj, attribute) except AttributeError: pass try: return obj[attribute] except (TypeError, LookupError, AttributeError): return self.undefined(obj=obj, name=attribute)
'Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates. If you are :ref:`developing Jinja2 extensions <writing-extensions>` this gives you a...
@internalcode def parse(self, source, name=None, filename=None):
try: return self._parse(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source)
'Internal parsing function used by `parse` and `compile`.'
def _parse(self, source, name, filename):
return Parser(self, source, name, _encode_filename(filename)).parse()
'Lex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development <writing-extensions>` and debugging templates. This does not perform preprocessing. If you want the preprocessing of the extensions to be applied...
def lex(self, source, name=None, filename=None):
source = unicode(source) try: return self.lexer.tokeniter(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source)
'Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized.'
def preprocess(self, source, name=None, filename=None):
return reduce((lambda s, e: e.preprocess(s, name, filename)), self.iter_extensions(), unicode(source))
'Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.'
def _tokenize(self, source, name, filename=None, state=None):
source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(source, name, filename, state) for ext in self.iter_extensions(): stream = ext.filter_stream(stream) if (not isinstance(stream, TokenStream)): stream = TokenStream(stream, name, filename) return str...
'Internal hook that can be overriden to hook a different generate method in. .. versionadded:: 2.5'
def _generate(self, source, name, filename, defer_init=False):
return generate(source, self, name, filename, defer_init=defer_init)
'Internal hook that can be overriden to hook a different compile method in. .. versionadded:: 2.5'
def _compile(self, source, filename):
return compile(source, filename, 'exec')
'Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or m...
@internalcode def compile(self, source, name=None, filename=None, raw=False, defer_init=False):
source_hint = None try: if isinstance(source, basestring): source_hint = source source = self._parse(source, name, filename) if self.optimized: source = optimize(source, self) source = self._generate(source, name, filename, defer_init=defer_init) ...
'A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env...
def compile_expression(self, source, undefined_to_none=True):
parser = Parser(self, source, state='variable') exc_info = None try: expr = parser.parse_expression() if (not parser.stream.eos): raise TemplateSyntaxError('chunk after expression', parser.stream.current.lineno, None, None) expr.set_environment(self) except Temp...
'Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, `zip` can be set to ``\'stored\'``. `extensions` and ...
def compile_templates(self, target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False):
from jinja2.loaders import ModuleLoader if (log_function is None): log_function = (lambda x: None) if py_compile: import imp, marshal py_header = (imp.get_magic() + u'\xff\xff\xff\xff'.encode('iso-8859-15')) def write_file(filename, data, mode): if zip: info =...
'Returns a list of templates for this environment. This requires that the loader supports the loader\'s :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list o...
def list_templates(self, extensions=None, filter_func=None):
x = self.loader.list_templates() if (extensions is not None): if (filter_func is not None): raise TypeError('either extensions or filter_func can be passed, but not both') filter_func = (lambda x: (('.' in x) and (x.rsplit('.', 1)[1] in extensions))) if...
'Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.'
def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
global _make_traceback if (exc_info is None): exc_info = sys.exc_info() if (_make_traceback is None): from jinja2.debug import make_traceback as _make_traceback traceback = _make_traceback(exc_info, source_hint) if (rendered and (self.exception_formatter is not None)): return...
'Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and impl...
def join_path(self, template, parent):
return template
'Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a :class:`Template`. If the `parent` parameter is not `None`, :meth:`join_path` is called to get the real template name before loading. The `globals` parameter can be used to provide template wide global...
@internalcode def get_template(self, name, parent=None, globals=None):
if isinstance(name, Template): return name if (parent is not None): name = self.join_path(name, parent) return self._load_template(name, self.make_globals(globals))
'Works like :meth:`get_template` but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a :exc:`TemplatesNotFound` exception. .. versionadded:: 2.3 .. versionchanged:: 2.4 If `names` contains a :class:`Template` object it is returned from the function unchanged.'
@internalcode def select_template(self, names, parent=None, globals=None):
if (not names): raise TemplatesNotFound(message=u'Tried to select from an empty list of templates.') globals = self.make_globals(globals) for name in names: if isinstance(name, Template): return name if (parent is not None): name = self...
'Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3'
@internalcode def get_or_select_template(self, template_name_or_list, parent=None, globals=None):
if isinstance(template_name_or_list, basestring): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals)
'Load a template from a string. This parses the source given and returns a :class:`Template` object.'
def from_string(self, source, globals=None, template_class=None):
globals = self.make_globals(globals) cls = (template_class or self.template_class) return cls.from_code(self, self.compile(source), globals, None)
'Return a dict for the globals.'
def make_globals(self, d):
if (not d): return self.globals return dict(self.globals, **d)
'Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object.'
@classmethod def from_code(cls, environment, code, globals, uptodate=None):
namespace = {'environment': environment, '__file__': code.co_filename} exec code in namespace rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv
'Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4'
@classmethod def from_module_dict(cls, environment, module_dict, globals):
return cls._from_namespace(environment, module_dict, globals)
'This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights=\'that say nih\') template.render({\'knights\': \'that say nih\'}) This will return the rende...
def render(self, *args, **kwargs):
vars = dict(*args, **kwargs) try: return concat(self.root_render_func(self.new_context(vars))) except Exception: exc_info = sys.exc_info() return self.environment.handle_exception(exc_info, True)
'Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.'
def stream(self, *args, **kwargs):
return TemplateStream(self.generate(*args, **kwargs))
'For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the same arguments as :meth:`render`...
def generate(self, *args, **kwargs):
vars = dict(*args, **kwargs) try: for event in self.root_render_func(self.new_context(vars)): (yield event) except Exception: exc_info = sys.exc_info() else: return (yield self.environment.handle_exception(exc_info, True))
'Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context without adding the globals. `locals` can be a dict of local variables for internal usage.'
def new_context(self, vars=None, shared=False, locals=None):
return new_context(self.environment, self.name, self.blocks, vars, shared, self.globals, locals)
'This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It\'s also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method.'
def make_module(self, vars=None, shared=False, locals=None):
return TemplateModule(self, self.new_context(vars, shared, locals))
'The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template(\'{% macro foo() %}42{% endmacro %}23\') >>> unicode(t.module) u\'23\' >>> t.module.foo() u\'42\''
@property def module(self):
if (self._module is not None): return self._module self._module = rv = self.make_module() return rv
'Return the source line number of a line number in the generated bytecode as they are not in sync.'
def get_corresponding_lineno(self, lineno):
for (template_line, code_line) in reversed(self.debug_info): if (code_line <= lineno): return template_line return 1
'If this variable is `False` there is a newer version available.'
@property def is_up_to_date(self):
if (self._uptodate is None): return True return self._uptodate()
'The debug info mapping.'
@property def debug_info(self):
return [tuple(map(int, x.split('='))) for x in self._debug_info.split('&')]
'Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specifiy an `encoding`. Example usage:: Template(\'Hello {{ name }}!\').stream(name=\'foo\').dump(\'hello.html\')'
def dump(self, fp, encoding=None, errors='strict'):
close = False if isinstance(fp, basestring): fp = file(fp, 'w') close = True try: if (encoding is not None): iterable = (x.encode(encoding, errors) for x in self) else: iterable = self if hasattr(fp, 'writelines'): fp.writelines(ite...
'Disable the output buffering.'
def disable_buffering(self):
self._next = self._gen.next self.buffered = False
'Enable buffering. Buffer `size` items before yielding them.'
def enable_buffering(self, size=5):
if (size <= 1): raise ValueError('buffer size too small') def generator(next): buf = [] c_size = 0 push = buf.append while 1: try: while (c_size < size): c = next() push(c) if...
'Eliminate dead code.'
def visit_If(self, node):
if (node.find(nodes.Block) is not None): return self.generic_visit(node) try: val = self.visit(node.test).as_const() except nodes.Impossible: return self.generic_visit(node) if val: body = node.body else: body = node.else_ result = [] for node in body:...
'Do constant folding.'
def fold(self, node):
node = self.generic_visit(node) try: return nodes.Const.from_untrusted(node.as_const(), lineno=node.lineno, environment=self.environment) except nodes.Impossible: return node
'Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u\'Main \xbb <em>About</em>\''
def unescape(self):
from jinja2._markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if (name in HTML_ENTITIES): return unichr(HTML_ENTITIES[name]) try: if (name[:2] in ('#x', '#X')): return unichr(int(name[2:], 16)) elif name...
'Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u\'Main \xbb About\''
def striptags(self):
stripped = u' '.join(_striptags_re.sub('', self).split()) return Markup(stripped).unescape()
'Escape the string. Works like :func:`escape` with the difference that for subclasses of :class:`Markup` this function would return the correct subclass.'
@classmethod def escape(cls, s):
rv = escape(s) if (rv.__class__ is not cls): return cls(rv) return rv
'Return a string with the traceback.'
def render_as_text(self, limit=None):
lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip()
'Return a unicode string with the traceback as rendered HTML.'
def render_as_html(self, full=False):
from jinja2.debugrenderer import render_traceback return (u'%s\n\n<!--\n%s\n-->' % (render_traceback(self, full=full), self.render_as_text().decode('utf-8', 'replace')))
'`True` if this is a template syntax error.'
@property def is_template_syntax_error(self):
return isinstance(self.exc_value, TemplateSyntaxError)
'Exception info tuple with a proxy around the frame objects.'
@property def exc_info(self):
return (self.exc_type, self.exc_value, self.frames[0])
'Standard python exc_info for re-raising'
@property def standard_exc_info(self):
tb = self.frames[0] if (type(tb) is not TracebackType): tb = tb.tb return (self.exc_type, self.exc_value, tb)
'Register a special name like `loop`.'
def add_special(self, name):
self.undeclared.discard(name) self.declared.add(name)
'Check if a name is declared in this or an outer scope.'
def is_declared(self, name):
if ((name in self.declared_locally) or (name in self.declared_parameter)): return True return (name in self.declared)
'Create a copy of the current one.'
def copy(self):
rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv
'Walk the node and check for identifiers. If the scope is hard (eg: enforce on a python level) overrides from outer scopes are tracked differently.'
def inspect(self, nodes):
visitor = FrameIdentifierVisitor(self.identifiers) for node in nodes: visitor.visit(node)
'Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped.'
def find_shadowed(self, extra=()):
i = self.identifiers return (((i.declared | i.outer_undeclared) & (i.declared_locally | i.declared_parameter)) | set((x for x in extra if i.is_declared(x))))
'Return an inner frame.'
def inner(self):
return Frame(self.eval_ctx, self)
'Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it\'s not a rootlevel frame any longer.'
def soft(self):
rv = self.copy() rv.rootlevel = False return rv
'All assignments to names go through this function.'
def visit_Name(self, node):
if (node.ctx == 'store'): self.identifiers.declared_locally.add(node.name) elif (node.ctx == 'param'): self.identifiers.declared_parameter.add(node.name) elif ((node.ctx == 'load') and (not self.identifiers.is_declared(node.name))): self.identifiers.undeclared.add(node.name)
'Visit assignments in the correct order.'
def visit_Assign(self, node):
self.visit(node.node) self.visit(node.target)
'Visiting stops at for blocks. However the block sequence is visited as part of the outer scope.'
def visit_For(self, node):
self.visit(node.iter)
'Fail with a :exc:`TemplateAssertionError`.'
def fail(self, msg, lineno):
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
'Get a new unique identifier.'
def temporary_identifier(self):
self._last_identifier += 1 return ('t_%d' % self._last_identifier)
'Enable buffering for the frame from that point onwards.'
def buffer(self, frame):
frame.buffer = self.temporary_identifier() self.writeline(('%s = []' % frame.buffer))
'Return the buffer contents of the frame.'
def return_buffer_contents(self, frame):
if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline(('return Markup(concat(%s))' % frame.buffer)) self.outdent() self.writeline('else:') self.indent() self.writeline(('return concat(%s)' % frame.b...
'Indent by one.'
def indent(self):
self._indentation += 1
'Outdent by step.'
def outdent(self, step=1):
self._indentation -= step
'Yield or write into the frame buffer.'
def start_write(self, frame, node=None):
if (frame.buffer is None): self.writeline('yield ', node) else: self.writeline(('%s.append(' % frame.buffer), node)
'End the writing process started by `start_write`.'
def end_write(self, frame):
if (frame.buffer is not None): self.write(')')