signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@property<EOL><INDENT>def cache(self):<DEDENT>
return self.template.cache<EOL>
Return the :class:`.Cache` object referenced by this :class:`.Namespace` object's :class:`.Template`.
f8230:c6:m5
def include_file(self, uri, **kwargs):
_include_file(self.context, uri, self._templateuri, **kwargs)<EOL>
Include a file at the given ``uri``.
f8230:c6:m6
@property<EOL><INDENT>def module(self):<DEDENT>
return self.template.module<EOL>
The Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, i.e. the generated module for the template.
f8230:c7:m1
@property<EOL><INDENT>def filename(self):<DEDENT>
return self.template.filename<EOL>
The path of the filesystem file used for this :class:`.Namespace`'s module or template.
f8230:c7:m2
@property<EOL><INDENT>def uri(self):<DEDENT>
return self.template.uri<EOL>
The URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. This is the equivalent of :attr:`.Template.uri`.
f8230:c7:m3
@property<EOL><INDENT>def filename(self):<DEDENT>
return self.module.__file__<EOL>
The path of the filesystem file used for this :class:`.Namespace`'s module or template.
f8230:c8:m1
def extract(fileobj, keywords, comment_tags, options):
extractor = BabelMakoExtractor(keywords, comment_tags, options)<EOL>for message in extractor(fileobj):<EOL><INDENT>yield message<EOL><DEDENT>
Extract messages from Mako templates. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples :rtype: ``iterator``
f8231:m0
def load_template(self, templatename, template_string=None):
if template_string is not None:<EOL><INDENT>return Template(template_string, **self.tmpl_options)<EOL><DEDENT>if '<STR_LIT:/>' not in templatename:<EOL><INDENT>templatename = '<STR_LIT:/>' + templatename.replace('<STR_LIT:.>', '<STR_LIT:/>') + '<STR_LIT:.>' +self.extension<EOL><DEDENT>return self.lookup.get_template(templatename)<EOL>
Loads a template from a file or a string
f8235:c0:m1
@staticmethod<EOL><INDENT>def _split_comment(lineno, comment):<DEDENT>
return [(lineno + index, line) for index, line in<EOL>enumerate(comment.splitlines())]<EOL>
Return the multiline comment at lineno split into a list of comment line numbers and the accompanying comment line
f8236:c0:m2
def convert_comments(text):
return re.sub(r'<STR_LIT>', "<STR_LIT>", text)<EOL>
preprocess old style comments. example: from mako.ext.preprocessors import convert_comments t = Template(..., preprocessor=convert_comments)
f8238:m0
def match(self, regexp, flags=None):
try:<EOL><INDENT>reg = _regexp_cache[(regexp, flags)]<EOL><DEDENT>except KeyError:<EOL><INDENT>if flags:<EOL><INDENT>reg = re.compile(regexp, flags)<EOL><DEDENT>else:<EOL><INDENT>reg = re.compile(regexp)<EOL><DEDENT>_regexp_cache[(regexp, flags)] = reg<EOL><DEDENT>return self.match_reg(reg)<EOL>
compile the given regexp, cache the reg, and call match_reg().
f8239:c0:m2
def match_reg(self, reg):
mp = self.match_position<EOL>match = reg.match(self.text, self.match_position)<EOL>if match:<EOL><INDENT>(start, end) = match.span()<EOL>if end == start:<EOL><INDENT>self.match_position = end + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.match_position = end<EOL><DEDENT>self.matched_lineno = self.lineno<EOL>lines = re.findall(r"<STR_LIT:\n>", self.text[mp:self.match_position])<EOL>cp = mp - <NUM_LIT:1><EOL>while (cp >= <NUM_LIT:0> and cp < self.textlength and self.text[cp] != '<STR_LIT:\n>'):<EOL><INDENT>cp -= <NUM_LIT:1><EOL><DEDENT>self.matched_charpos = mp - cp<EOL>self.lineno += len(lines)<EOL><DEDENT>return match<EOL>
match the given regular expression object to the current text position. if a match occurs, update the current text and line position.
f8239:c0:m3
def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
if isinstance(text, compat.text_type):<EOL><INDENT>m = self._coding_re.match(text)<EOL>encoding = m and m.group(<NUM_LIT:1>) or known_encoding or '<STR_LIT:ascii>'<EOL>return encoding, text<EOL><DEDENT>if text.startswith(codecs.BOM_UTF8):<EOL><INDENT>text = text[len(codecs.BOM_UTF8):]<EOL>parsed_encoding = '<STR_LIT:utf-8>'<EOL>m = self._coding_re.match(text.decode('<STR_LIT:utf-8>', '<STR_LIT:ignore>'))<EOL>if m is not None and m.group(<NUM_LIT:1>) != '<STR_LIT:utf-8>':<EOL><INDENT>raise exceptions.CompileException(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % m.group(<NUM_LIT:1>),<EOL>text.decode('<STR_LIT:utf-8>', '<STR_LIT:ignore>'),<EOL><NUM_LIT:0>, <NUM_LIT:0>, filename)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>m = self._coding_re.match(text.decode('<STR_LIT:utf-8>', '<STR_LIT:ignore>'))<EOL>if m:<EOL><INDENT>parsed_encoding = m.group(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>parsed_encoding = known_encoding or '<STR_LIT:ascii>'<EOL><DEDENT><DEDENT>if decode_raw:<EOL><INDENT>try:<EOL><INDENT>text = text.decode(parsed_encoding)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>raise exceptions.CompileException(<EOL>"<STR_LIT>" %<EOL>parsed_encoding,<EOL>text.decode('<STR_LIT:utf-8>', '<STR_LIT:ignore>'),<EOL><NUM_LIT:0>, <NUM_LIT:0>, filename)<EOL><DEDENT><DEDENT>return parsed_encoding, text<EOL>
given string/unicode or bytes/string, determine encoding from magic encoding comment, return body as unicode or raw if decode_raw=False
f8239:c0:m6
def match_comment(self):
match = self.match(r"<STR_LIT>", re.S)<EOL>if match:<EOL><INDENT>self.append_node(parsetree.Comment, match.group(<NUM_LIT:1>))<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
matches the multiline version of a comment
f8239:c0:m15
def get_argument_expressions(self, as_call=False):
namedecls = []<EOL>argnames = self.argnames[::-<NUM_LIT:1>]<EOL>kwargnames = self.kwargnames[::-<NUM_LIT:1>]<EOL>defaults = self.defaults[::-<NUM_LIT:1>]<EOL>kwdefaults = self.kwdefaults[::-<NUM_LIT:1>]<EOL>if self.kwargs:<EOL><INDENT>namedecls.append("<STR_LIT>" + kwargnames.pop(<NUM_LIT:0>))<EOL><DEDENT>for name in kwargnames:<EOL><INDENT>if as_call:<EOL><INDENT>namedecls.append("<STR_LIT>" % (name, name))<EOL><DEDENT>elif kwdefaults:<EOL><INDENT>default = kwdefaults.pop(<NUM_LIT:0>)<EOL>if default is None:<EOL><INDENT>namedecls.append(name)<EOL><DEDENT>else:<EOL><INDENT>namedecls.append("<STR_LIT>" % (<EOL>name, pyparser.ExpressionGenerator(default).value()))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>namedecls.append(name)<EOL><DEDENT><DEDENT>if self.varargs:<EOL><INDENT>namedecls.append("<STR_LIT:*>" + argnames.pop(<NUM_LIT:0>))<EOL><DEDENT>for name in argnames:<EOL><INDENT>if as_call or not defaults:<EOL><INDENT>namedecls.append(name)<EOL><DEDENT>else:<EOL><INDENT>default = defaults.pop(<NUM_LIT:0>)<EOL>namedecls.append("<STR_LIT>" % (<EOL>name, pyparser.ExpressionGenerator(default).value()))<EOL><DEDENT><DEDENT>namedecls.reverse()<EOL>return namedecls<EOL>
Return the argument declarations of this FunctionDecl as a printable list. By default the return value is appropriate for writing in a ``def``; set `as_call` to true to build arguments to be passed to the function instead (assuming locals with the same names as the arguments exist).
f8240:c3:m1
def with_metaclass(meta, base=object):
return meta("<STR_LIT>" % meta.__name__, (base,), {})<EOL>
Create a base class with a metaclass.
f8241:m2
def arg_stringname(func_arg):
if hasattr(func_arg, '<STR_LIT>'):<EOL><INDENT>return func_arg.arg<EOL><DEDENT>else:<EOL><INDENT>return str(func_arg)<EOL><DEDENT>
Gets the string name of a kwarg or vararg In Python3.4 a function's args are of _ast.arg type not _ast.name
f8241:m3
def legacy_html_escape(s):
s = s.replace("<STR_LIT:&>", "<STR_LIT>")<EOL>s = s.replace("<STR_LIT:>>", "<STR_LIT>")<EOL>s = s.replace("<STR_LIT:<>", "<STR_LIT>")<EOL>s = s.replace('<STR_LIT:">', "<STR_LIT>")<EOL>s = s.replace("<STR_LIT:'>", "<STR_LIT>")<EOL>return s<EOL>
legacy HTML escape for non-unicode mode.
f8242:m0
def htmlentityreplace_errors(ex):
if isinstance(ex, UnicodeEncodeError):<EOL><INDENT>bad_text = ex.object[ex.start:ex.end]<EOL>text = _html_entities_escaper.escape(bad_text)<EOL>return (compat.text_type(text), ex.end)<EOL><DEDENT>raise ex<EOL>
An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') 'The cost was &euro;12.'
f8242:m7
def escape_entities(self, text):
return compat.text_type(text).translate(self.codepoint2entity)<EOL>
Replace characters with their character entity references. Only characters corresponding to a named entity are replaced.
f8242:c1:m1
def escape(self, text):
return self.__escapable.sub(self.__escape, compat.text_type(text)<EOL>).encode('<STR_LIT:ascii>')<EOL>
Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII.
f8242:c1:m3
def unescape(self, text):
return self.__characterrefs.sub(self.__unescape, text)<EOL>
Unescape character references. All character references (both entity references and numerical character references) are unescaped.
f8242:c1:m5
def has_template(self, uri):
try:<EOL><INDENT>self.get_template(uri)<EOL>return True<EOL><DEDENT>except exceptions.TemplateLookupException:<EOL><INDENT>return False<EOL><DEDENT>
Return ``True`` if this :class:`.TemplateLookup` is capable of returning a :class:`.Template` object for the given ``uri``. :param uri: String URI of the template to be resolved.
f8243:c0:m0
def get_template(self, uri, relativeto=None):
raise NotImplementedError()<EOL>
Return a :class:`.Template` object corresponding to the given ``uri``. The default implementation raises :class:`.NotImplementedError`. Implementations should raise :class:`.TemplateLookupException` if the given ``uri`` cannot be resolved. :param uri: String URI of the template to be resolved. :param relativeto: if present, the given ``uri`` is assumed to be relative to this URI.
f8243:c0:m1
def filename_to_uri(self, uri, filename):
return uri<EOL>
Convert the given ``filename`` to a URI relative to this :class:`.TemplateCollection`.
f8243:c0:m2
def adjust_uri(self, uri, filename):
return uri<EOL>
Adjust the given ``uri`` based on the calling ``filename``. When this method is called from the runtime, the ``filename`` parameter is taken directly to the ``filename`` attribute of the calling template. Therefore a custom :class:`.TemplateCollection` subclass can place any string identifier desired in the ``filename`` parameter of the :class:`.Template` objects it constructs and have them come back here.
f8243:c0:m3
def get_template(self, uri):
try:<EOL><INDENT>if self.filesystem_checks:<EOL><INDENT>return self._check(uri, self._collection[uri])<EOL><DEDENT>else:<EOL><INDENT>return self._collection[uri]<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>u = re.sub(r'<STR_LIT>', '<STR_LIT>', uri)<EOL>for dir in self.directories:<EOL><INDENT>srcfile = posixpath.normpath(posixpath.join(dir, u))<EOL>if os.path.isfile(srcfile):<EOL><INDENT>return self._load(srcfile, uri)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.TopLevelLookupException(<EOL>"<STR_LIT>" % uri)<EOL><DEDENT><DEDENT>
Return a :class:`.Template` object corresponding to the given ``uri``. .. note:: The ``relativeto`` argument is not supported here at the moment.
f8243:c1:m1
def adjust_uri(self, uri, relativeto):
key = (uri, relativeto)<EOL>if key in self._uri_cache:<EOL><INDENT>return self._uri_cache[key]<EOL><DEDENT>if uri[<NUM_LIT:0>] != '<STR_LIT:/>':<EOL><INDENT>if relativeto is not None:<EOL><INDENT>v = self._uri_cache[key] = posixpath.join(<EOL>posixpath.dirname(relativeto), uri)<EOL><DEDENT>else:<EOL><INDENT>v = self._uri_cache[key] = '<STR_LIT:/>' + uri<EOL><DEDENT><DEDENT>else:<EOL><INDENT>v = self._uri_cache[key] = uri<EOL><DEDENT>return v<EOL>
Adjust the given ``uri`` based on the given relative URI.
f8243:c1:m2
def filename_to_uri(self, filename):
try:<EOL><INDENT>return self._uri_cache[filename]<EOL><DEDENT>except KeyError:<EOL><INDENT>value = self._relativeize(filename)<EOL>self._uri_cache[filename] = value<EOL>return value<EOL><DEDENT>
Convert the given ``filename`` to a URI relative to this :class:`.TemplateCollection`.
f8243:c1:m3
def _relativeize(self, filename):
filename = posixpath.normpath(filename)<EOL>for dir in self.directories:<EOL><INDENT>if filename[<NUM_LIT:0>:len(dir)] == dir:<EOL><INDENT>return filename[len(dir):]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Return the portion of a filename that is 'relative' to the directories in this lookup.
f8243:c1:m4
def put_string(self, uri, text):
self._collection[uri] = Template(<EOL>text,<EOL>lookup=self,<EOL>uri=uri,<EOL>**self.template_args)<EOL>
Place a new :class:`.Template` object into this :class:`.TemplateLookup`, based on the given string of ``text``.
f8243:c1:m7
def put_template(self, uri, template):
self._collection[uri] = template<EOL>
Place a new :class:`.Template` object into this :class:`.TemplateLookup`, based on the given :class:`.Template` object.
f8243:c1:m8
def compile(node,<EOL>uri,<EOL>filename=None,<EOL>default_filters=None,<EOL>buffer_filters=None,<EOL>imports=None,<EOL>future_imports=None,<EOL>source_encoding=None,<EOL>generate_magic_comment=True,<EOL>disable_unicode=False,<EOL>strict_undefined=False,<EOL>enable_loop=True,<EOL>reserved_names=frozenset()):
<EOL>if not compat.py3k and isinstance(source_encoding, compat.text_type):<EOL><INDENT>source_encoding = source_encoding.encode(source_encoding)<EOL><DEDENT>buf = util.FastEncodingBuffer()<EOL>printer = PythonPrinter(buf)<EOL>_GenerateRenderMethod(printer,<EOL>_CompileContext(uri,<EOL>filename,<EOL>default_filters,<EOL>buffer_filters,<EOL>imports,<EOL>future_imports,<EOL>source_encoding,<EOL>generate_magic_comment,<EOL>disable_unicode,<EOL>strict_undefined,<EOL>enable_loop,<EOL>reserved_names),<EOL>node)<EOL>return buf.getvalue()<EOL>
Generate module source code given a parsetree node, uri, and optional source filename
f8244:m0
def mangle_mako_loop(node, printer):
loop_variable = LoopVariable()<EOL>node.accept_visitor(loop_variable)<EOL>if loop_variable.detected:<EOL><INDENT>node.nodes[-<NUM_LIT:1>].has_loop_context = True<EOL>match = _FOR_LOOP.match(node.text)<EOL>if match:<EOL><INDENT>printer.writelines(<EOL>'<STR_LIT>' % match.group(<NUM_LIT:2>),<EOL>'<STR_LIT>'<EOL>)<EOL>text = '<STR_LIT>' % match.group(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxError("<STR_LIT>" % node.text)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>text = node.text<EOL><DEDENT>return text<EOL>
converts a for loop into a context manager wrapped around a for loop when access to the `loop` variable has been detected in the for loop body
f8244:m1
def write_toplevel(self):
inherit = []<EOL>namespaces = {}<EOL>module_code = []<EOL>self.compiler.pagetag = None<EOL>class FindTopLevel(object):<EOL><INDENT>def visitInheritTag(s, node):<EOL><INDENT>inherit.append(node)<EOL><DEDENT>def visitNamespaceTag(s, node):<EOL><INDENT>namespaces[node.name] = node<EOL><DEDENT>def visitPageTag(s, node):<EOL><INDENT>self.compiler.pagetag = node<EOL><DEDENT>def visitCode(s, node):<EOL><INDENT>if node.ismodule:<EOL><INDENT>module_code.append(node)<EOL><DEDENT><DEDENT><DEDENT>f = FindTopLevel()<EOL>for n in self.node.nodes:<EOL><INDENT>n.accept_visitor(f)<EOL><DEDENT>self.compiler.namespaces = namespaces<EOL>module_ident = set()<EOL>for n in module_code:<EOL><INDENT>module_ident = module_ident.union(n.declared_identifiers())<EOL><DEDENT>module_identifiers = _Identifiers(self.compiler)<EOL>module_identifiers.declared = module_ident<EOL>if self.compiler.generate_magic_comment andself.compiler.source_encoding:<EOL><INDENT>self.printer.writeline("<STR_LIT>" %<EOL>self.compiler.source_encoding)<EOL><DEDENT>if self.compiler.future_imports:<EOL><INDENT>self.printer.writeline("<STR_LIT>" %<EOL>("<STR_LIT:U+002CU+0020>".join(self.compiler.future_imports),))<EOL><DEDENT>self.printer.writeline("<STR_LIT>")<EOL>self.printer.writeline("<STR_LIT>")<EOL>self.printer.writeline("<STR_LIT>")<EOL>self.printer.writeline("<STR_LIT>")<EOL>self.printer.writeline("<STR_LIT>" % MAGIC_NUMBER)<EOL>self.printer.writeline("<STR_LIT>" % time.time())<EOL>self.printer.writeline("<STR_LIT>" % self.compiler.enable_loop)<EOL>self.printer.writeline(<EOL>"<STR_LIT>" % self.compiler.filename)<EOL>self.printer.writeline("<STR_LIT>" % self.compiler.uri)<EOL>self.printer.writeline(<EOL>"<STR_LIT>" % self.compiler.source_encoding)<EOL>if self.compiler.imports:<EOL><INDENT>buf = '<STR_LIT>'<EOL>for imp in self.compiler.imports:<EOL><INDENT>buf += imp + "<STR_LIT:\n>"<EOL>self.printer.writeline(imp)<EOL><DEDENT>impcode = ast.PythonCode(<EOL>buf,<EOL>source='<STR_LIT>', lineno=<NUM_LIT:0>,<EOL>pos=<NUM_LIT:0>,<EOL>filename='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>impcode = None<EOL><DEDENT>main_identifiers = module_identifiers.branch(self.node)<EOL>module_identifiers.topleveldefs =module_identifiers.topleveldefs.union(main_identifiers.topleveldefs)<EOL>module_identifiers.declared.add("<STR_LIT>")<EOL>if impcode:<EOL><INDENT>module_identifiers.declared.update(impcode.declared_identifiers)<EOL><DEDENT>self.compiler.identifiers = module_identifiers<EOL>self.printer.writeline("<STR_LIT>" %<EOL>[n.name for n in<EOL>main_identifiers.topleveldefs.values()]<EOL>)<EOL>self.printer.write_blanks(<NUM_LIT:2>)<EOL>if len(module_code):<EOL><INDENT>self.write_module_code(module_code)<EOL><DEDENT>if len(inherit):<EOL><INDENT>self.write_namespaces(namespaces)<EOL>self.write_inherit(inherit[-<NUM_LIT:1>])<EOL><DEDENT>elif len(namespaces):<EOL><INDENT>self.write_namespaces(namespaces)<EOL><DEDENT>return list(main_identifiers.topleveldefs.values())<EOL>
Traverse a template structure for module-level directives and generate the start of module-level code.
f8244:c1:m3
def write_render_callable(self, node, name, args, buffered, filtered,<EOL>cached):
if self.in_def:<EOL><INDENT>decorator = node.decorator<EOL>if decorator:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>" % decorator)<EOL><DEDENT><DEDENT>self.printer.start_source(node.lineno)<EOL>self.printer.writelines(<EOL>"<STR_LIT>" % (name, '<STR_LIT:U+002C>'.join(args)),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>)<EOL>if buffered or filtered or cached:<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL><DEDENT>self.identifier_stack.append(<EOL>self.compiler.identifiers.branch(self.node))<EOL>if (not self.in_def or self.node.is_block) and '<STR_LIT>' in args:<EOL><INDENT>self.identifier_stack[-<NUM_LIT:1>].argument_declared.add('<STR_LIT>')<EOL><DEDENT>if not self.in_def and (<EOL>len(self.identifiers.locally_assigned) > <NUM_LIT:0> or<EOL>len(self.identifiers.argument_declared) > <NUM_LIT:0><EOL>):<EOL><INDENT>self.printer.writeline("<STR_LIT>" %<EOL>'<STR_LIT:U+002C>'.join([<EOL>"<STR_LIT>" % (x, x) for x in<EOL>self.identifiers.argument_declared<EOL>]))<EOL><DEDENT>self.write_variable_declares(self.identifiers, toplevel=True)<EOL>for n in self.node.nodes:<EOL><INDENT>n.accept_visitor(self)<EOL><DEDENT>self.write_def_finish(self.node, buffered, filtered, cached)<EOL>self.printer.writeline(None)<EOL>self.printer.write_blanks(<NUM_LIT:2>)<EOL>if cached:<EOL><INDENT>self.write_cache_decorator(<EOL>node, name,<EOL>args, buffered,<EOL>self.identifiers, toplevel=True)<EOL><DEDENT>
write a top-level render callable. this could be the main render() method or that of a top-level def.
f8244:c1:m4
def write_module_code(self, module_code):
for n in module_code:<EOL><INDENT>self.printer.start_source(n.lineno)<EOL>self.printer.write_indented_block(n.text)<EOL><DEDENT>
write module-level template code, i.e. that which is enclosed in <%! %> tags in the template.
f8244:c1:m5
def write_inherit(self, node):
self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" %<EOL>(node.parsed_attributes['<STR_LIT:file>']),<EOL>None<EOL>)<EOL>
write the module-level inheritance-determination callable.
f8244:c1:m6
def write_namespaces(self, namespaces):
self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>None, None<EOL>)<EOL>self.printer.writeline("<STR_LIT>")<EOL>for node in namespaces.values():<EOL><INDENT>if '<STR_LIT>' in node.attributes:<EOL><INDENT>self.compiler.has_ns_imports = True<EOL><DEDENT>self.printer.start_source(node.lineno)<EOL>if len(node.nodes):<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL>export = []<EOL>identifiers = self.compiler.identifiers.branch(node)<EOL>self.in_def = True<EOL>class NSDefVisitor(object):<EOL><INDENT>def visitDefTag(s, node):<EOL><INDENT>s.visitDefOrBase(node)<EOL><DEDENT>def visitBlockTag(s, node):<EOL><INDENT>s.visitDefOrBase(node)<EOL><DEDENT>def visitDefOrBase(s, node):<EOL><INDENT>if node.is_anonymous:<EOL><INDENT>raise exceptions.CompileException(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>**node.exception_kwargs<EOL>)<EOL><DEDENT>self.write_inline_def(node, identifiers, nested=False)<EOL>export.append(node.funcname)<EOL><DEDENT><DEDENT>vis = NSDefVisitor()<EOL>for n in node.nodes:<EOL><INDENT>n.accept_visitor(vis)<EOL><DEDENT>self.printer.writeline("<STR_LIT>" % ('<STR_LIT:U+002C>'.join(export)))<EOL>self.printer.writeline(None)<EOL>self.in_def = False<EOL>callable_name = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>callable_name = "<STR_LIT:None>"<EOL><DEDENT>if '<STR_LIT:file>' in node.parsed_attributes:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(<EOL>node.name,<EOL>node.parsed_attributes.get('<STR_LIT:file>', '<STR_LIT:None>'),<EOL>callable_name,<EOL>)<EOL>)<EOL><DEDENT>elif '<STR_LIT>' in node.parsed_attributes:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(<EOL>node.name,<EOL>callable_name,<EOL>node.parsed_attributes.get(<EOL>'<STR_LIT>', '<STR_LIT:None>')<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(<EOL>node.name,<EOL>callable_name,<EOL>)<EOL>)<EOL><DEDENT>if eval(node.attributes.get('<STR_LIT>', "<STR_LIT:False>")):<EOL><INDENT>self.printer.writeline("<STR_LIT>" % (node.name))<EOL><DEDENT>self.printer.writeline(<EOL>"<STR_LIT>" % repr(node.name))<EOL>self.printer.write_blanks(<NUM_LIT:1>)<EOL><DEDENT>if not len(namespaces):<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL><DEDENT>self.printer.writeline(None)<EOL>
write the module-level namespace-generating callable.
f8244:c1:m7
def write_variable_declares(self, identifiers, toplevel=False, limit=None):
<EOL>comp_idents = dict([(c.funcname, c) for c in identifiers.defs])<EOL>to_write = set()<EOL>to_write = to_write.union(identifiers.undeclared)<EOL>to_write = to_write.union(<EOL>[c.funcname for c in identifiers.closuredefs.values()])<EOL>to_write = to_write.difference(identifiers.argument_declared)<EOL>to_write = to_write.difference(identifiers.locally_declared)<EOL>if self.compiler.enable_loop:<EOL><INDENT>has_loop = "<STR_LIT>" in to_write<EOL>to_write.discard("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>has_loop = False<EOL><DEDENT>if limit is not None:<EOL><INDENT>to_write = to_write.intersection(limit)<EOL><DEDENT>if toplevel and getattr(self.compiler, '<STR_LIT>', False):<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL>self.compiler.has_imports = True<EOL>for ident, ns in self.compiler.namespaces.items():<EOL><INDENT>if '<STR_LIT>' in ns.attributes:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(<EOL>ident,<EOL>re.split(r'<STR_LIT>', ns.attributes['<STR_LIT>'])<EOL>))<EOL><DEDENT><DEDENT><DEDENT>if has_loop:<EOL><INDENT>self.printer.writeline(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>for ident in to_write:<EOL><INDENT>if ident in comp_idents:<EOL><INDENT>comp = comp_idents[ident]<EOL>if comp.is_block:<EOL><INDENT>if not comp.is_anonymous:<EOL><INDENT>self.write_def_decl(comp, identifiers)<EOL><DEDENT>else:<EOL><INDENT>self.write_inline_def(comp, identifiers, nested=True)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if comp.is_root():<EOL><INDENT>self.write_def_decl(comp, identifiers)<EOL><DEDENT>else:<EOL><INDENT>self.write_inline_def(comp, identifiers, nested=True)<EOL><DEDENT><DEDENT><DEDENT>elif ident in self.compiler.namespaces:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>" %<EOL>(ident, ident)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>if getattr(self.compiler, '<STR_LIT>', False):<EOL><INDENT>if self.compiler.strict_undefined:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>" %<EOL>(ident, ident),<EOL>"<STR_LIT>" % ident,<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" % (ident, ident),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" %<EOL>ident,<EOL>None, None<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>" %<EOL>(ident, ident, ident))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.compiler.strict_undefined:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" % (ident, ident),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" %<EOL>ident,<EOL>None<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>" % (ident, ident)<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.printer.writeline("<STR_LIT>")<EOL>
write variable declarations at the top of a function. the variable declarations are in the form of callable definitions for defs and/or name lookup within the function's context argument. the names declared are based on the names that are referenced in the function body, which don't otherwise have any explicit assignment operation. names that are assigned within the body are assumed to be locally-scoped variables and are not separately declared. for def callable definitions, if the def is a top-level callable then a 'stub' callable is generated which wraps the current Context into a closure. if the def is not top-level, it is fully rendered as a local closure.
f8244:c1:m8
def write_def_decl(self, node, identifiers):
funcname = node.funcname<EOL>namedecls = node.get_argument_expressions()<EOL>nameargs = node.get_argument_expressions(as_call=True)<EOL>if not self.in_def and (<EOL>len(self.identifiers.locally_assigned) > <NUM_LIT:0> or<EOL>len(self.identifiers.argument_declared) > <NUM_LIT:0>):<EOL><INDENT>nameargs.insert(<NUM_LIT:0>, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>nameargs.insert(<NUM_LIT:0>, '<STR_LIT>')<EOL><DEDENT>self.printer.writeline("<STR_LIT>" % (funcname, "<STR_LIT:U+002C>".join(namedecls)))<EOL>self.printer.writeline(<EOL>"<STR_LIT>" % (funcname, "<STR_LIT:U+002C>".join(nameargs)))<EOL>self.printer.writeline(None)<EOL>
write a locally-available callable referencing a top-level def
f8244:c1:m9
def write_inline_def(self, node, identifiers, nested):
namedecls = node.get_argument_expressions()<EOL>decorator = node.decorator<EOL>if decorator:<EOL><INDENT>self.printer.writeline(<EOL>"<STR_LIT>" % decorator)<EOL><DEDENT>self.printer.writeline(<EOL>"<STR_LIT>" % (node.funcname, "<STR_LIT:U+002C>".join(namedecls)))<EOL>filtered = len(node.filter_args.args) > <NUM_LIT:0><EOL>buffered = eval(node.attributes.get('<STR_LIT>', '<STR_LIT:False>'))<EOL>cached = eval(node.attributes.get('<STR_LIT>', '<STR_LIT:False>'))<EOL>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>)<EOL>if buffered or filtered or cached:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT>identifiers = identifiers.branch(node, nested=nested)<EOL>self.write_variable_declares(identifiers)<EOL>self.identifier_stack.append(identifiers)<EOL>for n in node.nodes:<EOL><INDENT>n.accept_visitor(self)<EOL><DEDENT>self.identifier_stack.pop()<EOL>self.write_def_finish(node, buffered, filtered, cached)<EOL>self.printer.writeline(None)<EOL>if cached:<EOL><INDENT>self.write_cache_decorator(node, node.funcname,<EOL>namedecls, False, identifiers,<EOL>inline=True, toplevel=False)<EOL><DEDENT>
write a locally-available def callable inside an enclosing def.
f8244:c1:m10
def write_def_finish(self, node, buffered, filtered, cached,<EOL>callstack=True):
if not buffered and not cached and not filtered:<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL>if callstack:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>None<EOL>)<EOL><DEDENT><DEDENT>if buffered or filtered or cached:<EOL><INDENT>if buffered or cached:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if callstack:<EOL><INDENT>self.printer.writeline("<STR_LIT>")<EOL><DEDENT>s = "<STR_LIT>"<EOL>if filtered:<EOL><INDENT>s = self.create_filter_callable(node.filter_args.args, s,<EOL>False)<EOL><DEDENT>self.printer.writeline(None)<EOL>if buffered and not cached:<EOL><INDENT>s = self.create_filter_callable(self.compiler.buffer_filters,<EOL>s, False)<EOL><DEDENT>if buffered or cached:<EOL><INDENT>self.printer.writeline("<STR_LIT>" % s)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>" % s,<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>
write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block if any, and writes code to retrieve captured content, apply filters, send proper return value.
f8244:c1:m11
def write_cache_decorator(self, node_or_pagetag, name,<EOL>args, buffered, identifiers,<EOL>inline=False, toplevel=False):
self.printer.writeline("<STR_LIT>" % (name, name))<EOL>cachekey = node_or_pagetag.parsed_attributes.get('<STR_LIT>',<EOL>repr(name))<EOL>cache_args = {}<EOL>if self.compiler.pagetag is not None:<EOL><INDENT>cache_args.update(<EOL>(<EOL>pa[<NUM_LIT:6>:],<EOL>self.compiler.pagetag.parsed_attributes[pa]<EOL>)<EOL>for pa in self.compiler.pagetag.parsed_attributes<EOL>if pa.startswith('<STR_LIT>') and pa != '<STR_LIT>'<EOL>)<EOL><DEDENT>cache_args.update(<EOL>(<EOL>pa[<NUM_LIT:6>:],<EOL>node_or_pagetag.parsed_attributes[pa]<EOL>) for pa in node_or_pagetag.parsed_attributes<EOL>if pa.startswith('<STR_LIT>') and pa != '<STR_LIT>'<EOL>)<EOL>if '<STR_LIT>' in cache_args:<EOL><INDENT>cache_args['<STR_LIT>'] = int(eval(cache_args['<STR_LIT>']))<EOL><DEDENT>self.printer.writeline("<STR_LIT>" % (name, '<STR_LIT:U+002C>'.join(args)))<EOL>pass_args = [<EOL>"<STR_LIT>" % ((a.split('<STR_LIT:=>')[<NUM_LIT:0>],) * <NUM_LIT:2>) if '<STR_LIT:=>' in a else a<EOL>for a in args<EOL>]<EOL>self.write_variable_declares(<EOL>identifiers,<EOL>toplevel=toplevel,<EOL>limit=node_or_pagetag.undeclared_identifiers()<EOL>)<EOL>if buffered:<EOL><INDENT>s = "<STR_LIT>""<STR_LIT>""<STR_LIT>" % (<EOL>cachekey, name, '<STR_LIT:U+002C>'.join(pass_args),<EOL>'<STR_LIT>'.join(["<STR_LIT>" % (k, v)<EOL>for k, v in cache_args.items()]),<EOL>name<EOL>)<EOL>s = self.create_filter_callable(self.compiler.buffer_filters, s,<EOL>False)<EOL>self.printer.writelines("<STR_LIT>" + s, None)<EOL><DEDENT>else:<EOL><INDENT>self.printer.writelines(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(<EOL>cachekey, name, '<STR_LIT:U+002C>'.join(pass_args),<EOL>'<STR_LIT>'.join(["<STR_LIT>" % (k, v)<EOL>for k, v in cache_args.items()]),<EOL>name,<EOL>),<EOL>"<STR_LIT>",<EOL>None<EOL>)<EOL><DEDENT>
write a post-function decorator to replace a rendering callable with a cached version of itself.
f8244:c1:m12
def create_filter_callable(self, args, target, is_expression):
def locate_encode(name):<EOL><INDENT>if re.match(r'<STR_LIT>', name):<EOL><INDENT>return "<STR_LIT>" + name<EOL><DEDENT>elif self.compiler.disable_unicode:<EOL><INDENT>return filters.NON_UNICODE_ESCAPES.get(name, name)<EOL><DEDENT>else:<EOL><INDENT>return filters.DEFAULT_ESCAPES.get(name, name)<EOL><DEDENT><DEDENT>if '<STR_LIT:n>' not in args:<EOL><INDENT>if is_expression:<EOL><INDENT>if self.compiler.pagetag:<EOL><INDENT>args = self.compiler.pagetag.filter_args.args + args<EOL><DEDENT>if self.compiler.default_filters:<EOL><INDENT>args = self.compiler.default_filters + args<EOL><DEDENT><DEDENT><DEDENT>for e in args:<EOL><INDENT>if e == '<STR_LIT:n>':<EOL><INDENT>continue<EOL><DEDENT>m = re.match(r'<STR_LIT>', e)<EOL>if m:<EOL><INDENT>ident, fargs = m.group(<NUM_LIT:1>, <NUM_LIT:2>)<EOL>f = locate_encode(ident)<EOL>e = f + fargs<EOL><DEDENT>else:<EOL><INDENT>e = locate_encode(e)<EOL>assert e is not None<EOL><DEDENT>target = "<STR_LIT>" % (e, target)<EOL><DEDENT>return target<EOL>
write a filter-applying expression based on the filters present in the given filter names, adjusting for the global 'default' filter aliases as needed.
f8244:c1:m13
def branch(self, node, **kwargs):
return _Identifiers(self.compiler, node, self, **kwargs)<EOL>
create a new Identifiers for a new Node, with this Identifiers as the parent.
f8244:c2:m1
def check_declared(self, node):
for ident in node.undeclared_identifiers():<EOL><INDENT>if ident != '<STR_LIT>' andident not in self.declared.union(self.locally_declared):<EOL><INDENT>self.undeclared.add(ident)<EOL><DEDENT><DEDENT>for ident in node.declared_identifiers():<EOL><INDENT>self.locally_declared.add(ident)<EOL><DEDENT>
update the state of this Identifiers with the undeclared and declared identifiers of the given node.
f8244:c2:m4
def parse(expr, filename='<STR_LIT>', mode='<STR_LIT>'):
return compile(expr, filename, mode, PyCF_ONLY_AST)<EOL>
Parse an expression into an AST node.
f8245:m0
def to_source(node, indent_with='<STR_LIT:U+0020>' * <NUM_LIT:4>):
generator = SourceGenerator(indent_with)<EOL>generator.visit(node)<EOL>return '<STR_LIT>'.join(generator.result)<EOL>
This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is that the AST contains some more data than regular sourcecode does, which is dropped during conversion. Each level of indentation is replaced with `indent_with`. Per default this parameter is equal to four spaces as suggested by PEP 8, but it might be adjusted to match the application's styleguide.
f8245:m1
def dump(node):
def _format(node):<EOL><INDENT>if isinstance(node, AST):<EOL><INDENT>return '<STR_LIT>' % (node.__class__.__name__,<EOL>'<STR_LIT:U+002CU+0020>'.join('<STR_LIT>' % (a, _format(b))<EOL>for a, b in iter_fields(node)))<EOL><DEDENT>elif isinstance(node, list):<EOL><INDENT>return '<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(_format(x) for x in node)<EOL><DEDENT>return repr(node)<EOL><DEDENT>if not isinstance(node, AST):<EOL><INDENT>raise TypeError('<STR_LIT>' % node.__class__.__name__)<EOL><DEDENT>return _format(node)<EOL>
A very verbose representation of the node passed. This is useful for debugging purposes.
f8245:m2
def copy_location(new_node, old_node):
for attr in '<STR_LIT>', '<STR_LIT>':<EOL><INDENT>if attr in old_node._attributes and attr in new_node._attributesand hasattr(old_node, attr):<EOL><INDENT>setattr(new_node, attr, getattr(old_node, attr))<EOL><DEDENT><DEDENT>return new_node<EOL>
Copy the source location hint (`lineno` and `col_offset`) from the old to the new node if possible and return the new one.
f8245:m3
def fix_missing_locations(node):
def _fix(node, lineno, col_offset):<EOL><INDENT>if '<STR_LIT>' in node._attributes:<EOL><INDENT>if not hasattr(node, '<STR_LIT>'):<EOL><INDENT>node.lineno = lineno<EOL><DEDENT>else:<EOL><INDENT>lineno = node.lineno<EOL><DEDENT><DEDENT>if '<STR_LIT>' in node._attributes:<EOL><INDENT>if not hasattr(node, '<STR_LIT>'):<EOL><INDENT>node.col_offset = col_offset<EOL><DEDENT>else:<EOL><INDENT>col_offset = node.col_offset<EOL><DEDENT><DEDENT>for child in iter_child_nodes(node):<EOL><INDENT>_fix(child, lineno, col_offset)<EOL><DEDENT><DEDENT>_fix(node, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>return node<EOL>
Some nodes require a line number and the column offset. Without that information the compiler will abort the compilation. Because it can be a dull task to add appropriate line numbers and column offsets when adding new nodes this function can help. It copies the line number and column offset of the parent node to the child nodes without this information. Unlike `copy_location` this works recursive and won't touch nodes that already have a location information.
f8245:m4
def increment_lineno(node, n=<NUM_LIT:1>):
for node in zip((node,), walk(node)):<EOL><INDENT>if '<STR_LIT>' in node._attributes:<EOL><INDENT>node.lineno = getattr(node, '<STR_LIT>', <NUM_LIT:0>) + n<EOL><DEDENT><DEDENT>
Increment the line numbers of all nodes by `n` if they have line number attributes. This is useful to "move code" to a different location in a file.
f8245:m5
def iter_fields(node):
<EOL>if not hasattr(node, '<STR_LIT>') or not node._fields:<EOL><INDENT>return<EOL><DEDENT>for field in node._fields:<EOL><INDENT>try:<EOL><INDENT>yield field, getattr(node, field)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Iterate over all fields of a node, only yielding existing fields.
f8245:m6
def get_fields(node):
return dict(iter_fields(node))<EOL>
Like `iter_fiels` but returns a dict.
f8245:m7
def iter_child_nodes(node):
for name, field in iter_fields(node):<EOL><INDENT>if isinstance(field, AST):<EOL><INDENT>yield field<EOL><DEDENT>elif isinstance(field, list):<EOL><INDENT>for item in field:<EOL><INDENT>if isinstance(item, AST):<EOL><INDENT>yield item<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Iterate over all child nodes or a node.
f8245:m8
def get_child_nodes(node):
return list(iter_child_nodes(node))<EOL>
Like `iter_child_nodes` but returns a list.
f8245:m9
def get_compile_mode(node):
if not isinstance(node, mod):<EOL><INDENT>raise TypeError('<STR_LIT>' % node.__class__.__name__)<EOL><DEDENT>return {<EOL>Expression: '<STR_LIT>',<EOL>Interactive: '<STR_LIT>'<EOL>}.get(node.__class__, '<STR_LIT>')<EOL>
Get the mode for `compile` of a given node. If the node is not a `mod` node (`Expression`, `Module` etc.) a `TypeError` is thrown.
f8245:m10
def get_docstring(node):
if not isinstance(node, (FunctionDef, ClassDef, Module)):<EOL><INDENT>raise TypeError("<STR_LIT>" % node.__class__.__name__)<EOL><DEDENT>if node.body and isinstance(node.body[<NUM_LIT:0>], Str):<EOL><INDENT>return node.body[<NUM_LIT:0>].s<EOL><DEDENT>
Return the docstring for the given node or `None` if no docstring can be found. If the node provided does not accept docstrings a `TypeError` will be raised.
f8245:m11
def walk(node):
from collections import deque<EOL>todo = deque([node])<EOL>while todo:<EOL><INDENT>node = todo.popleft()<EOL>todo.extend(iter_child_nodes(node))<EOL>yield node<EOL><DEDENT>
Iterate over all nodes. This is useful if you only want to modify nodes in place and don't care about the context or the order the nodes are returned.
f8245:m12
def get_visitor(self, node):
method = '<STR_LIT>' + node.__class__.__name__<EOL>return getattr(self, method, None)<EOL>
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.
f8245:c0:m0
def visit(self, node):
f = self.get_visitor(node)<EOL>if f is not None:<EOL><INDENT>return f(node)<EOL><DEDENT>return self.generic_visit(node)<EOL>
Visit a node.
f8245:c0:m1
def generic_visit(self, node):
for field, value in iter_fields(node):<EOL><INDENT>if isinstance(value, list):<EOL><INDENT>for item in value:<EOL><INDENT>if isinstance(item, AST):<EOL><INDENT>self.visit(item)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(value, AST):<EOL><INDENT>self.visit(value)<EOL><DEDENT><DEDENT>
Called if no explicit visitor function exists for a node.
f8245:c0:m2
@property<EOL><INDENT>def source(self):<DEDENT>
return _get_module_info_from_callable(self.callable_).source<EOL>
Return the template source code for this :class:`.Template`.
f8247:c0:m4
@property<EOL><INDENT>def code(self):<DEDENT>
return _get_module_info_from_callable(self.callable_).code<EOL>
Return the module source code for this :class:`.Template`.
f8247:c0:m5
def render(self, *args, **data):
return runtime._render(self, self.callable_, args, data)<EOL>
Render the output of this template as a string. If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw output uses `cStringIO` and can't handle multibyte characters). A :class:`.Context` object is created corresponding to the given data. Arguments that are explicitly declared by this template's internal rendering method are also pulled from the given ``*args``, ``**data`` members.
f8247:c0:m10
def render_unicode(self, *args, **data):
return runtime._render(self,<EOL>self.callable_,<EOL>args,<EOL>data,<EOL>as_unicode=True)<EOL>
Render the output of this template as a unicode object.
f8247:c0:m11
def render_context(self, context, *args, **kwargs):
if getattr(context, '<STR_LIT>', None) is None:<EOL><INDENT>context._set_with_template(self)<EOL><DEDENT>runtime._render_context(self,<EOL>self.callable_,<EOL>context,<EOL>*args,<EOL>**kwargs)<EOL>
Render this :class:`.Template` with the given context. The data is written to the context's buffer.
f8247:c0:m12
def get_def(self, name):
return DefTemplate(self, getattr(self.module, "<STR_LIT>" % name))<EOL>
Return a def of this template as a :class:`.DefTemplate`.
f8247:c0:m14
def parse(code, mode='<STR_LIT>', **exception_kwargs):
try:<EOL><INDENT>return _ast_util.parse(code, '<STR_LIT>', mode)<EOL><DEDENT>except Exception:<EOL><INDENT>raise exceptions.SyntaxException(<EOL>"<STR_LIT>" % (<EOL>compat.exception_as().__class__.__name__,<EOL>compat.exception_as(),<EOL>code[<NUM_LIT:0>:<NUM_LIT:50>]<EOL>), **exception_kwargs)<EOL><DEDENT>
Parse an expression into AST
f8248:m0
def is_ternary(self, keyword):
return keyword in {<EOL>'<STR_LIT>':set(['<STR_LIT>', '<STR_LIT>']),<EOL>'<STR_LIT>':set(['<STR_LIT>', '<STR_LIT>']),<EOL>'<STR_LIT>':set(['<STR_LIT>'])<EOL>}.get(self.keyword, [])<EOL>
return true if the given keyword is a ternary keyword for this ControlLine
f8250:c2:m4
def __init__(self, keyword, attributes, expressions,<EOL>nonexpressions, required, **kwargs):
super(Tag, self).__init__(**kwargs)<EOL>self.keyword = keyword<EOL>self.attributes = attributes<EOL>self._parse_attributes(expressions, nonexpressions)<EOL>missing = [r for r in required if r not in self.parsed_attributes]<EOL>if len(missing):<EOL><INDENT>raise exceptions.CompileException(<EOL>"<STR_LIT>" %<EOL>"<STR_LIT:U+002C>".join([repr(m) for m in missing]),<EOL>**self.exception_kwargs)<EOL><DEDENT>self.parent = None<EOL>self.nodes = []<EOL>
construct a new Tag instance. this constructor not called directly, and is only called by subclasses. :param keyword: the tag keyword :param attributes: raw dictionary of attribute key/value pairs :param expressions: a set of identifiers that are legal attributes, which can also contain embedded expressions :param nonexpressions: a set of identifiers that are legal attributes, which cannot contain embedded expressions :param \**kwargs: other arguments passed to the Node superclass (lineno, pos)
f8250:c8:m0
def adjust_whitespace(text):
state = [False, False]<EOL>(backslashed, triplequoted) = (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>def in_multi_line(line):<EOL><INDENT>start_state = (state[backslashed] or state[triplequoted])<EOL>if re.search(r"<STR_LIT>", line):<EOL><INDENT>state[backslashed] = True<EOL><DEDENT>else:<EOL><INDENT>state[backslashed] = False<EOL><DEDENT>def match(reg, t):<EOL><INDENT>m = re.match(reg, t)<EOL>if m:<EOL><INDENT>return m, t[len(m.group(<NUM_LIT:0>)):]<EOL><DEDENT>else:<EOL><INDENT>return None, t<EOL><DEDENT><DEDENT>while line:<EOL><INDENT>if state[triplequoted]:<EOL><INDENT>m, line = match(r"<STR_LIT:%s>" % state[triplequoted], line)<EOL>if m:<EOL><INDENT>state[triplequoted] = False<EOL><DEDENT>else:<EOL><INDENT>m, line = match(r"<STR_LIT>" % state[triplequoted], line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>m, line = match(r'<STR_LIT:#>', line)<EOL>if m:<EOL><INDENT>return start_state<EOL><DEDENT>m, line = match(r"<STR_LIT>", line)<EOL>if m:<EOL><INDENT>state[triplequoted] = m.group(<NUM_LIT:0>)<EOL>continue<EOL><DEDENT>m, line = match(r"<STR_LIT>", line)<EOL><DEDENT><DEDENT>return start_state<EOL><DEDENT>def _indent_line(line, stripspace='<STR_LIT>'):<EOL><INDENT>return re.sub(r"<STR_LIT>" % stripspace, '<STR_LIT>', line)<EOL><DEDENT>lines = []<EOL>stripspace = None<EOL>for line in re.split(r'<STR_LIT>', text):<EOL><INDENT>if in_multi_line(line):<EOL><INDENT>lines.append(line)<EOL><DEDENT>else:<EOL><INDENT>line = line.expandtabs()<EOL>if stripspace is None and re.search(r"<STR_LIT>", line):<EOL><INDENT>stripspace = re.match(r"<STR_LIT>", line).group(<NUM_LIT:1>)<EOL><DEDENT>lines.append(_indent_line(line, stripspace))<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(lines)<EOL>
remove the left-whitespace margin of a block of Python code.
f8251:m0
def write_indented_block(self, block):
self.in_indent_lines = False<EOL>for l in re.split(r'<STR_LIT>', block):<EOL><INDENT>self.line_buffer.append(l)<EOL>self._update_lineno(<NUM_LIT:1>)<EOL><DEDENT>
print a line or lines of python which already contain indentation. The indentation of the total block of lines will be adjusted to that of the current indent level.
f8251:c0:m4
def writelines(self, *lines):
for line in lines:<EOL><INDENT>self.writeline(line)<EOL><DEDENT>
print a series of lines of python.
f8251:c0:m5
def writeline(self, line):
if not self.in_indent_lines:<EOL><INDENT>self._flush_adjusted_lines()<EOL>self.in_indent_lines = True<EOL><DEDENT>if (line is None or<EOL>re.match(r"<STR_LIT>",line) or<EOL>re.match(r"<STR_LIT>", line)<EOL>):<EOL><INDENT>hastext = False<EOL><DEDENT>else:<EOL><INDENT>hastext = True<EOL><DEDENT>is_comment = line and len(line) and line[<NUM_LIT:0>] == '<STR_LIT:#>'<EOL>if (not is_comment and<EOL>(not hastext or self._is_unindentor(line))<EOL>):<EOL><INDENT>if self.indent > <NUM_LIT:0>:<EOL><INDENT>self.indent -= <NUM_LIT:1><EOL>if len(self.indent_detail) == <NUM_LIT:0>:<EOL><INDENT>raise exceptions.SyntaxException(<EOL>"<STR_LIT>")<EOL><DEDENT>self.indent_detail.pop()<EOL><DEDENT><DEDENT>if line is None:<EOL><INDENT>return<EOL><DEDENT>self.stream.write(self._indent_line(line) + "<STR_LIT:\n>")<EOL>self._update_lineno(len(line.split("<STR_LIT:\n>")))<EOL>if re.search(r"<STR_LIT>", line):<EOL><INDENT>match = re.match(r"<STR_LIT>", line)<EOL>if match:<EOL><INDENT>indentor = match.group(<NUM_LIT:1>)<EOL>self.indent += <NUM_LIT:1><EOL>self.indent_detail.append(indentor)<EOL><DEDENT>else:<EOL><INDENT>indentor = None<EOL>m2 = re.match(r"<STR_LIT>",<EOL>line)<EOL>if m2:<EOL><INDENT>self.indent += <NUM_LIT:1><EOL>self.indent_detail.append(indentor)<EOL><DEDENT><DEDENT><DEDENT>
print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of the line.
f8251:c0:m6
def close(self):
self._flush_adjusted_lines()<EOL>
close this printer, flushing any remaining lines.
f8251:c0:m7
def _is_unindentor(self, line):
<EOL>if len(self.indent_detail) == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>indentor = self.indent_detail[-<NUM_LIT:1>]<EOL>if indentor is None:<EOL><INDENT>return False<EOL><DEDENT>match = re.match(r"<STR_LIT>", line)<EOL>if not match:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
return true if the given line is an 'unindentor', relative to the last 'indent' event received.
f8251:c0:m8
def _indent_line(self, line, stripspace='<STR_LIT>'):
return re.sub(r"<STR_LIT>" % stripspace, self.indentstring<EOL>* self.indent, line)<EOL>
indent the given line according to the current indent level. stripspace is a string of space that will be truncated from the start of the line before indenting.
f8251:c0:m9
def _reset_multi_line_flags(self):
self.backslashed, self.triplequoted = False, False<EOL>
reset the flags which would indicate we are in a backslashed or triple-quoted section.
f8251:c0:m10
def _in_multi_line(self, line):
<EOL>current_state = (self.backslashed or self.triplequoted)<EOL>if re.search(r"<STR_LIT>", line):<EOL><INDENT>self.backslashed = True<EOL><DEDENT>else:<EOL><INDENT>self.backslashed = False<EOL><DEDENT>triples = len(re.findall(r"<STR_LIT>", line))<EOL>if triples == <NUM_LIT:1> or triples % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>self.triplequoted = not self.triplequoted<EOL><DEDENT>return current_state<EOL>
return true if the given line is part of a multi-line block, via backslash or triple-quote.
f8251:c0:m11
def text_error_template(lookup=None):
import mako.template<EOL>return mako.template.Template(
Provides a template that renders a stack trace in a similar format to the Python interpreter, substituting source template filenames, line numbers and code for that of the originating source template, as applicable.
f8252:m1
def html_error_template():
import mako.template<EOL>return mako.template.Template(
Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The template has two options. With the ``full`` option disabled, only a section of an HTML document is returned. With the ``css`` option disabled, the default stylesheet won't be included.
f8252:m5
def _init_message(self):
try:<EOL><INDENT>self.message = compat.text_type(self.error)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>try:<EOL><INDENT>self.message = str(self.error)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>self.message = self.error.args[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if not isinstance(self.message, compat.text_type):<EOL><INDENT>self.message = compat.text_type(self.message, '<STR_LIT:ascii>', '<STR_LIT:replace>')<EOL><DEDENT>
Find a unicode representation of self.error
f8252:c8:m2
@property<EOL><INDENT>def traceback(self):<DEDENT>
return list(self._get_reformatted_records(self.records))<EOL>
Return a list of 4-tuple traceback records (i.e. normal python format) with template-corresponding lines remapped to the originating template.
f8252:c8:m4
@property<EOL><INDENT>def reverse_traceback(self):<DEDENT>
return list(self._get_reformatted_records(self.reverse_records))<EOL>
Return the same data as traceback, except in reverse order.
f8252:c8:m6
def _init(self, trcback):
import mako.template<EOL>mods = {}<EOL>rawrecords = traceback.extract_tb(trcback)<EOL>new_trcback = []<EOL>for filename, lineno, function, line in rawrecords:<EOL><INDENT>if not line:<EOL><INDENT>line = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>(line_map, template_lines) = mods[filename]<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>info = mako.template._get_module_info(filename)<EOL>module_source = info.code<EOL>template_source = info.source<EOL>template_filename = info.template_filename or filename<EOL><DEDENT>except KeyError:<EOL><INDENT>if not compat.py3k:<EOL><INDENT>try:<EOL><INDENT>fp = open(filename, '<STR_LIT:rb>')<EOL>encoding = util.parse_encoding(fp)<EOL>fp.close()<EOL><DEDENT>except IOError:<EOL><INDENT>encoding = None<EOL><DEDENT>if encoding:<EOL><INDENT>line = line.decode(encoding)<EOL><DEDENT>else:<EOL><INDENT>line = line.decode('<STR_LIT:ascii>', '<STR_LIT:replace>')<EOL><DEDENT><DEDENT>new_trcback.append((filename, lineno, function, line,<EOL>None, None, None, None))<EOL>continue<EOL><DEDENT>template_ln = <NUM_LIT:1><EOL>source_map = mako.template.ModuleInfo.get_module_source_metadata(<EOL>module_source, full_line_map=True)<EOL>line_map = source_map['<STR_LIT>']<EOL>template_lines = [line for line in<EOL>template_source.split("<STR_LIT:\n>")]<EOL>mods[filename] = (line_map, template_lines)<EOL><DEDENT>template_ln = line_map[lineno - <NUM_LIT:1>]<EOL>if template_ln <= len(template_lines):<EOL><INDENT>template_line = template_lines[template_ln - <NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>template_line = None<EOL><DEDENT>new_trcback.append((filename, lineno, function,<EOL>line, template_filename, template_ln,<EOL>template_line, template_source))<EOL><DEDENT>if not self.source:<EOL><INDENT>for l in range(len(new_trcback) - <NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if new_trcback[l][<NUM_LIT:5>]:<EOL><INDENT>self.source = new_trcback[l][<NUM_LIT:7>]<EOL>self.lineno = new_trcback[l][<NUM_LIT:5>]<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if new_trcback:<EOL><INDENT>try:<EOL><INDENT>fp = open(new_trcback[-<NUM_LIT:1>][<NUM_LIT:0>], '<STR_LIT:rb>')<EOL>encoding = util.parse_encoding(fp)<EOL>fp.seek(<NUM_LIT:0>)<EOL>self.source = fp.read()<EOL>fp.close()<EOL>if encoding:<EOL><INDENT>self.source = self.source.decode(encoding)<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>self.source = '<STR_LIT>'<EOL><DEDENT>self.lineno = new_trcback[-<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>return new_trcback<EOL>
format a traceback from sys.exc_info() into 7-item tuples, containing the regular four traceback tuple items, plus the original template filename, the line number adjusted relative to the template source, and code line from that line number of the template.
f8252:c8:m7
def scan(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_token():<EOL><INDENT>yield loader.get_token()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Scan a YAML stream and produce scanning tokens.
f8263:m0
def parse(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_event():<EOL><INDENT>yield loader.get_event()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Parse a YAML stream and produce parsing events.
f8263:m1
def compose(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>return loader.get_single_node()<EOL><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Parse the first YAML document in a stream and produce the corresponding representation tree.
f8263:m2
def compose_all(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_node():<EOL><INDENT>yield loader.get_node()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Parse all YAML documents in a stream and produce corresponding representation trees.
f8263:m3
def load(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>return loader.get_single_data()<EOL><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Parse the first YAML document in a stream and produce the corresponding Python object.
f8263:m4
def load_all(stream, Loader=Loader):
loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_data():<EOL><INDENT>yield loader.get_data()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>
Parse all YAML documents in a stream and produce corresponding Python objects.
f8263:m5
def safe_load(stream):
return load(stream, SafeLoader)<EOL>
Parse the first YAML document in a stream and produce the corresponding Python object. Resolve only basic YAML tags.
f8263:m6
def safe_load_all(stream):
return load_all(stream, SafeLoader)<EOL>
Parse all YAML documents in a stream and produce corresponding Python objects. Resolve only basic YAML tags.
f8263:m7
def emit(events, stream=None, Dumper=Dumper,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None):
getvalue = None<EOL>if stream is None:<EOL><INDENT>from StringIO import StringIO<EOL>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break)<EOL>try:<EOL><INDENT>for event in events:<EOL><INDENT>dumper.emit(event)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
f8263:m8
def serialize_all(nodes, stream=None, Dumper=Dumper,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None,<EOL>encoding='<STR_LIT:utf-8>', explicit_start=None, explicit_end=None,<EOL>version=None, tags=None):
getvalue = None<EOL>if stream is None:<EOL><INDENT>if encoding is None:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>else:<EOL><INDENT>from cStringIO import StringIO<EOL><DEDENT>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break,<EOL>encoding=encoding, version=version, tags=tags,<EOL>explicit_start=explicit_start, explicit_end=explicit_end)<EOL>try:<EOL><INDENT>dumper.open()<EOL>for node in nodes:<EOL><INDENT>dumper.serialize(node)<EOL><DEDENT>dumper.close()<EOL><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>
Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.
f8263:m9
def serialize(node, stream=None, Dumper=Dumper, **kwds):
return serialize_all([node], stream, Dumper=Dumper, **kwds)<EOL>
Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead.
f8263:m10
def dump_all(documents, stream=None, Dumper=Dumper,<EOL>default_style=None, default_flow_style=None,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None,<EOL>encoding='<STR_LIT:utf-8>', explicit_start=None, explicit_end=None,<EOL>version=None, tags=None):
getvalue = None<EOL>if stream is None:<EOL><INDENT>if encoding is None:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>else:<EOL><INDENT>from cStringIO import StringIO<EOL><DEDENT>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, default_style=default_style,<EOL>default_flow_style=default_flow_style,<EOL>canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break,<EOL>encoding=encoding, version=version, tags=tags,<EOL>explicit_start=explicit_start, explicit_end=explicit_end)<EOL>try:<EOL><INDENT>dumper.open()<EOL>for data in documents:<EOL><INDENT>dumper.represent(data)<EOL><DEDENT>dumper.close()<EOL><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
f8263:m11
def dump(data, stream=None, Dumper=Dumper, **kwds):
return dump_all([data], stream, Dumper=Dumper, **kwds)<EOL>
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
f8263:m12