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... | 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(te... | 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 = ... | 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:ut... | 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 k... | 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 €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 ... | 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
... | 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.n... | 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._u... | 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... | 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>tex... | 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):<EO... | 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>... | 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<... | 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_w... | 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 d... | 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>... | 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>... | 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.writ... | 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
ret... | 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 i... | 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 '... | 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 c... | 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(... | 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>'):<EO... | 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 th... | 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
t... | 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_L... | 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,
wh... | 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>... | 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(... | 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>:<E... | 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
``'htmlentityreplac... | 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):<... | 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... | 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:<E... | 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=widt... | 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_... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.