1. Atsushi Odagiri
  2. mako-inheritance

Commits

Ben Trofatter  committed 08def4d

Brought all modules into PEP 8 width compliance

  • Participants
  • Parent commits 749ac69
  • Branches default

Comments (0)

Files changed (14)

File mako/ast.py

View file
     def __init__(self, code, **exception_kwargs):
         self.code = code
  
-        # represents all identifiers which are assigned to at some point in the code
+        # represents all identifiers which are assigned to at some point in
+        # the code
         self.declared_identifiers = set()
  
-        # represents all identifiers which are referenced before their assignment, if any
+        # represents all identifiers which are referenced before their
+        # assignment, if any
         self.undeclared_identifiers = set()
  
-        # note that an identifier can be in both the undeclared and declared lists.
+        # note that an identifier can be in both the undeclared and declared
+        # lists.
 
         # using AST to parse instead of using code.co_varnames, 
         # code.co_names has several advantages:
         f.visit(expr)
  
 class PythonFragment(PythonCode):
-    """extends PythonCode to provide identifier lookups in partial control statements
+    """extends PythonCode to provide identifier lookups in partial control
+    statements
  
     e.g. 
         for x in 5:
         m = re.match(r'^(\w+)(?:\s+(.*?))?:\s*(#|$)', code.strip(), re.S)
         if not m:
             raise exceptions.CompileException(
-                            "Fragment '%s' is not a partial control statement" % 
-                            code, **exception_kwargs)
+                          "Fragment '%s' is not a partial control statement" % 
+                          code, **exception_kwargs)
         if m.group(3):
             code = code[:m.start(3)]
         (keyword, expr) = m.group(1,2)
         f.visit(expr)
         if not hasattr(self, 'funcname'):
             raise exceptions.CompileException(
-                                "Code '%s' is not a function declaration" % code,
-                                **exception_kwargs)
+                              "Code '%s' is not a function declaration" % code,
+                              **exception_kwargs)
         if not allow_kwargs and self.kwargs:
             raise exceptions.CompileException(
                                 "'**%s' keyword argument not allowed here" % 
                                 self.argnames[-1], **exception_kwargs)
  
     def get_argument_expressions(self, include_defaults=True):
-        """return the argument declarations of this FunctionDecl as a printable list."""
+        """return the argument declarations of this FunctionDecl as a printable
+        list."""
  
         namedecls = []
         defaults = [d for d in self.defaults]
     """the argument portion of a function declaration"""
  
     def __init__(self, code, **kwargs):
-        super(FunctionArgs, self).__init__("def ANON(%s):pass" % code, **kwargs)
+        super(FunctionArgs, self).__init__("def ANON(%s):pass" % code,
+                **kwargs)

File mako/cache.py

View file
         self.impl.invalidate(key, **self._get_cache_kw(kw))
  
     def invalidate_body(self):
-        """Invalidate the cached content of the "body" method for this template.
+        """Invalidate the cached content of the "body" method for this
+        template.
  
         """
         self.invalidate('render_body', __M_defname='render_body')
  
     def invalidate_def(self, name):
-        """Invalidate the cached content of a particular <%def> within this template."""
+        """Invalidate the cached content of a particular <%def> within this
+        template.
+        
+        """
  
         self.invalidate('render_%s' % name, __M_defname='render_%s' % name)
  

File mako/codegen.py

View file
 # This module is part of Mako and is released under
 # the MIT License: http://www.opensource.org/licenses/mit-license.php
 
-"""provides functionality for rendering a parsetree constructing into module source code."""
+"""provides functionality for rendering a parsetree constructing into module
+source code."""
 
 import time
 import re
 
         return main_identifiers.topleveldefs.values()
 
-    def write_render_callable(self, node, name, args, buffered, filtered, cached):
+    def write_render_callable(self, node, name, args, buffered, filtered,
+            cached):
         """write a top-level render callable.
  
         this could be the main render() method or that of a top-level def."""
         if self.in_def:
             decorator = node.decorator
             if decorator:
-                self.printer.writeline("@runtime._decorate_toplevel(%s)" % decorator)
+                self.printer.writeline(
+                                 "@runtime._decorate_toplevel(%s)" % decorator)
  
         self.printer.writelines(
             "def %s(%s):" % (name, ','.join(args)),
         if buffered or filtered or cached:
             self.printer.writeline("context._push_buffer()")
  
-        self.identifier_stack.append(self.compiler.identifiers.branch(self.node))
+        self.identifier_stack.append(
+                                   self.compiler.identifiers.branch(self.node))
         if (not self.in_def or self.node.is_block) and '**pageargs' in args:
             self.identifier_stack[-1].argument_declared.add('pageargs')
 
                     def visitDefOrBase(s, node):
                         if node.is_anonymous:
                             raise exceptions.CompileException(
-                                "Can't put anonymous blocks inside <%namespace>", 
+                                "Can't put anonymous blocks inside "
+                                "<%namespace>",
                                 **node.exception_kwargs
                             )
                         self.write_inline_def(node, identifiers, nested=False)
 
             if 'file' in node.parsed_attributes:
                 self.printer.writeline(
-                                "ns = runtime.TemplateNamespace(%r, context._clean_inheritance_tokens(),"
-                                " templateuri=%s, callables=%s, calling_uri=_template_uri)" %
+                                "ns = runtime.TemplateNamespace(%r,"
+                                " context._clean_inheritance_tokens(),"
+                                " templateuri=%s, callables=%s, "
+                                " calling_uri=_template_uri)" %
                                 (
-                                    node.name,
-                                    node.parsed_attributes.get('file', 'None'), 
-                                    callable_name, 
+                                   node.name,
+                                   node.parsed_attributes.get('file', 'None'), 
+                                   callable_name, 
                                 )
                             )
             elif 'module' in node.parsed_attributes:
                 self.printer.writeline(
-                                "ns = runtime.ModuleNamespace(%r, context._clean_inheritance_tokens(),"
-                                " callables=%s, calling_uri=_template_uri, module=%s)" %
+                                "ns = runtime.ModuleNamespace(%r,"
+                                " context._clean_inheritance_tokens(),"
+                                " callables=%s, calling_uri=_template_uri,"
+                                " module=%s)" %
                                 (
-                                    node.name,
-                                    callable_name, 
-                                    node.parsed_attributes.get('module', 'None')
+                                   node.name,
+                                   callable_name, 
+                                   node.parsed_attributes.get('module', 'None')
                                 )
                             )
             else:
                 self.printer.writeline(
-                                "ns = runtime.Namespace(%r, context._clean_inheritance_tokens(),"
+                                "ns = runtime.Namespace(%r,"
+                                " context._clean_inheritance_tokens(),"
                                 " callables=%s, calling_uri=_template_uri)" %
                                 (
                                     node.name,
             if eval(node.attributes.get('inheritable', "False")):
                 self.printer.writeline("context['self'].%s = ns" % (node.name))
  
-            self.printer.writeline("context.namespaces[(__name__, %s)] = ns" % repr(node.name))
+            self.printer.writeline(
+                   "context.namespaces[(__name__, %s)] = ns" % repr(node.name))
             self.printer.write("\n")
         if not len(namespaces):
             self.printer.writeline("pass")
  
         # write closure functions for closures that we define 
         # right here
-        to_write = to_write.union([c.funcname for c in identifiers.closuredefs.values()])
+        to_write = to_write.union(
+                        [c.funcname for c in identifiers.closuredefs.values()])
 
         # remove identifiers that are declared in the argument 
         # signature of the callable
             for ident, ns in self.compiler.namespaces.iteritems():
                 if ns.attributes.has_key('import'):
                     self.printer.writeline(
-                            "_mako_get_namespace(context, %r)._populate(_import_ns, %r)" %
+                            "_mako_get_namespace(context, %r)."\
+                                    "_populate(_import_ns, %r)" %
                             (
                                 ident,
                                 re.split(r'\s*,\s*', ns.attributes['import'])
                         )
                     else:
                         self.printer.writeline(
-                        "%s = _import_ns.get(%r, context.get(%r, UNDEFINED))" % 
+                        "%s = _import_ns.get(%r, context.get(%r, UNDEFINED))" %
                         (ident, ident, ident))
                 else:
                     if self.compiler.strict_undefined:
         self.printer.writeline("__M_writer = context.writer()")
  
     def write_source_comment(self, node):
-        """write a source comment containing the line number of the corresponding template line."""
+        """write a source comment containing the line number of the
+        corresponding template line."""
         if self.last_source_line != node.lineno:
             self.printer.writeline("# SOURCE LINE %d" % node.lineno)
             self.last_source_line = node.lineno
         else:
             nameargs.insert(0, 'context')
         self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls)))
-        self.printer.writeline("return render_%s(%s)" % (funcname, ",".join(nameargs)))
+        self.printer.writeline(
+                       "return render_%s(%s)" % (funcname, ",".join(nameargs)))
         self.printer.writeline(None)
  
     def write_inline_def(self, node, identifiers, nested):
  
         decorator = node.decorator
         if decorator:
-            self.printer.writeline("@runtime._decorate_inline(context, %s)" % decorator)
-        self.printer.writeline("def %s(%s):" % (node.funcname, ",".join(namedecls)))
+            self.printer.writeline(
+                          "@runtime._decorate_inline(context, %s)" % decorator)
+        self.printer.writeline(
+                          "def %s(%s):" % (node.funcname, ",".join(namedecls)))
         filtered = len(node.filter_args.args) > 0 
         buffered = eval(node.attributes.get('buffered', 'False'))
         cached = eval(node.attributes.get('cached', 'False'))
                                         namedecls, False, identifiers, 
                                         inline=True, toplevel=False)
  
-    def write_def_finish(self, node, buffered, filtered, cached, callstack=True):
-        """write the end section of a rendering function, either outermost or inline.
+    def write_def_finish(self, node, buffered, filtered, cached,
+            callstack=True):
+        """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."""
+        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."""
  
         if not buffered and not cached and not filtered:
             self.printer.writeline("return ''")
                 )
             else:
                 self.printer.writelines(
-                    "finally:",
-                        "__M_buf, __M_writer = context._pop_buffer_and_writer()"
+                   "finally:",
+                       "__M_buf, __M_writer = context._pop_buffer_and_writer()"
                 )
  
             if callstack:
  
             s = "__M_buf.getvalue()"
             if filtered:
-                s = self.create_filter_callable(node.filter_args.args, s, False)
+                s = self.create_filter_callable(node.filter_args.args, s,
+                                                False)
             self.printer.writeline(None)
             if buffered and not cached:
-                s = self.create_filter_callable(self.compiler.buffer_filters, s, False)
+                s = self.create_filter_callable(self.compiler.buffer_filters,
+                                                s, False)
             if buffered or cached:
                 self.printer.writeline("return %s" % s)
             else:
             callable with a cached version of itself."""
  
         self.printer.writeline("__M_%s = %s" % (name, name))
-        cachekey = node_or_pagetag.parsed_attributes.get('cache_key', repr(name))
+        cachekey = node_or_pagetag.parsed_attributes.get('cache_key',
+                                                         repr(name))
 
         cache_args = {}
         if self.compiler.pagetag is not None:
                             limit=node_or_pagetag.undeclared_identifiers()
                         )
         if buffered:
-            s = "context.get('local')."\
-                "cache.get_or_create(%s, lambda:__M_%s(%s),  %s__M_defname=%r)" % \
-                            (cachekey, name, ','.join(pass_args), 
-                            ''.join(["%s=%s, " % (k,v) for k, v in cache_args.items()]), 
-                            name
-                            )
+            s = "context.get('local').cache."\
+                   "get_or_create(%s, lambda:__M_%s(%s),  %s__M_defname=%r)" %\
+                   (cachekey, name, ','.join(pass_args), 
+                   ''.join(["%s=%s, " % (k,v) for k, v in cache_args.items()]),
+                   name
+                   )
             # apply buffer_filters
-            s = self.create_filter_callable(self.compiler.buffer_filters, s, False)
+            s = self.create_filter_callable(self.compiler.buffer_filters, s,
+                                            False)
             self.printer.writelines("return " + s,None)
         else:
             self.printer.writelines(
-                    "__M_writer(context.get('local')."
-                    "cache.get_or_create(%s, lambda:__M_%s(%s), %s__M_defname=%r))" % 
-                    (cachekey, name, ','.join(pass_args), 
-                    ''.join(["%s=%s, " % (k,v) for k, v in cache_args.items()]), 
-                    name, 
-                    ),
-                    "return ''",
+                   "__M_writer(context.get('local')."
+                   "cache.get_or_create(%s, lambda:__M_%s(%s), "
+                   "%s__M_defname=%r))" %
+                   (cachekey, name, ','.join(pass_args),
+                   ''.join(["%s=%s, " % (k,v) for k, v in cache_args.items()]),
+                   name, 
+                   ),
+                   "return ''",
                 None
             )
 
                 ) or \
                 len(self.compiler.default_filters):
  
-            s = self.create_filter_callable(node.escapes_code.args, "%s" % node.text, True)
+            s = self.create_filter_callable(node.escapes_code.args,
+                                            "%s" % node.text, True)
             self.printer.writeline("__M_writer(%s)" % s)
         else:
             self.printer.writeline("__M_writer(%s)" % node.text)
                 # declared/modified variables into the "__M_locals" dictionary,
                 # which is used for def calls within the same template, 
                 # to simulate "enclosing scope"
-                self.printer.writeline('__M_locals_builtin_stored = __M_locals_builtin()')
                 self.printer.writeline(
-                            '__M_locals.update(__M_dict_builtin([(__M_key,'
-                            ' __M_locals_builtin_stored[__M_key]) for '
-                            '__M_key in [%s] if __M_key in __M_locals_builtin_stored]))' %
-                            ','.join([repr(x) for x in node.declared_identifiers()]))
+                      '__M_locals_builtin_stored = __M_locals_builtin()')
+                self.printer.writeline(
+                      '__M_locals.update(__M_dict_builtin([(__M_key,'
+                      ' __M_locals_builtin_stored[__M_key]) for __M_key in'
+                      ' [%s] if __M_key in __M_locals_builtin_stored]))' %
+                      ','.join([repr(x) for x in node.declared_identifiers()]))
 
     def visitIncludeTag(self, node):
         self.write_source_comment(node)
         args = node.attributes.get('args')
         if args:
             self.printer.writeline(
-                        "runtime._include_file(context, %s, _template_uri, %s)" %
-                        (node.parsed_attributes['file'], args))
+                      "runtime._include_file(context, %s, _template_uri, %s)" %
+                      (node.parsed_attributes['file'], args))
         else:
             self.printer.writeline(
                         "runtime._include_file(context, %s, _template_uri)" %
             nameargs = node.get_argument_expressions(include_defaults=False)
             nameargs += ['**pageargs']
             self.printer.writeline("if 'parent' not in context._data or "
-                                    "not hasattr(context._data['parent'], '%s'):" 
-                                    % node.funcname)
-            self.printer.writeline("context['self'].%s(%s)" % (node.funcname, ",".join(nameargs)))
+                                  "not hasattr(context._data['parent'], '%s'):"
+                                  % node.funcname)
+            self.printer.writeline(
+                "context['self'].%s(%s)" % (node.funcname, ",".join(nameargs)))
             self.printer.writeline("\n")
 
     def visitCallNamespaceTag(self, node):
                 self.write_inline_def(node, callable_identifiers, nested=False)
                 if not node.is_anonymous:
                     export.append(node.funcname)
-                # remove defs that are within the <%call> from the "closuredefs" defined
-                # in the body, so they dont render twice
+                # remove defs that are within the <%call> from the
+                # "closuredefs" defined in the body, so they dont render twice
                 if node.funcname in body_identifiers.closuredefs:
                     del body_identifiers.closuredefs[node.funcname]
 
         self.printer.writelines(
             # push on caller for nested call
             "context.caller_stack.nextcaller = "
-                "runtime.Namespace('caller', context, callables=ccall(__M_caller))",
+                "runtime.Namespace('caller', context, "
+                                  "callables=ccall(__M_caller))",
             "try:")
         self.write_source_comment(node)
         self.printer.writelines(
-                "__M_writer(%s)" % self.create_filter_callable([], node.expression, True),
+                "__M_writer(%s)" % self.create_filter_callable(
+                                                    [], node.expression, True),
             "finally:",
                 "context.caller_stack.nextcaller = None",
             None
                 # things that have already been declared 
                 # in an enclosing namespace (i.e. names we can just use)
                 self.declared = set(parent.declared).\
-                                        union([c.name for c in parent.closuredefs.values()]).\
-                                        union(parent.locally_declared).\
-                                        union(parent.argument_declared)
+                         union([c.name for c in parent.closuredefs.values()]).\
+                         union(parent.locally_declared).\
+                         union(parent.argument_declared)
  
                 # if these identifiers correspond to a "nested" 
                 # scope, it means whatever the parent identifiers 
         if node is not None:
             node.accept_visitor(self)
 
-        illegal_names = self.compiler.reserved_names.intersection(self.locally_declared)
+        illegal_names = self.compiler.reserved_names.intersection(
+                                                         self.locally_declared)
         if illegal_names:
             raise exceptions.NameConflictError(
                 "Reserved words declared in template: %s" % 
  
     def __repr__(self):
         return "Identifiers(declared=%r, locally_declared=%r, "\
-                "undeclared=%r, topleveldefs=%r, closuredefs=%r, argumentdeclared=%r)" %\
+                "undeclared=%r, topleveldefs=%r, closuredefs=%r, "\
+                "argumentdeclared=%r)" %\
                 (
                     list(self.declared),
                     list(self.locally_declared),
             and declared identifiers of the given node."""
  
         for ident in node.undeclared_identifiers():
-            if ident != 'context' and ident not in self.declared.union(self.locally_declared):
+            if ident != 'context' and\
+                       ident not in self.declared.union(self.locally_declared):
                 self.undeclared.add(ident)
         for ident in node.declared_identifiers():
             self.locally_declared.add(ident)
     def visitCode(self, node):
         if not node.ismodule:
             self.check_declared(node)
-            self.locally_assigned = self.locally_assigned.union(node.declared_identifiers())
+            self.locally_assigned = self.locally_assigned.union(
+                                                   node.declared_identifiers())
  
     def visitNamespaceTag(self, node):
         # only traverse into the sub-elements of a 
             self._check_name_exists(self.closuredefs, node)
 
         for ident in node.undeclared_identifiers():
-            if ident != 'context' and ident not in self.declared.union(self.locally_declared):
+            if ident != 'context' and\
+                       ident not in self.declared.union(self.locally_declared):
                 self.undeclared.add(ident)
  
         # visit defs only one level deep
                 raise exceptions.CompileException(
                         "Named block '%s' not allowed inside of def '%s'" 
                         % (node.name, self.node.name), **node.exception_kwargs)
-            elif isinstance(self.node, (parsetree.CallTag, parsetree.CallNamespaceTag)):
+            elif isinstance(self.node,
+                            (parsetree.CallTag, parsetree.CallNamespaceTag)):
                 raise exceptions.CompileException(
                         "Named block '%s' not allowed inside of <%%call> tag" 
                         % (node.name, ), **node.exception_kwargs)
 
         for ident in node.undeclared_identifiers():
-            if ident != 'context' and ident not in self.declared.union(self.locally_declared):
+            if ident != 'context' and\
+                       ident not in self.declared.union(self.locally_declared):
                 self.undeclared.add(ident)
  
         if not node.is_anonymous:
     def visitCallTag(self, node):
         if node is self.node:
             for ident in node.undeclared_identifiers():
-                if ident != 'context' and ident not in self.declared.union(self.locally_declared):
+                if ident != 'context' and\
+                       ident not in self.declared.union(self.locally_declared):
                     self.undeclared.add(ident)
             for ident in node.declared_identifiers():
                 self.argument_declared.add(ident)
                 n.accept_visitor(self)
         else:
             for ident in node.undeclared_identifiers():
-                if ident != 'context' and ident not in self.declared.union(self.locally_declared):
+                if ident != 'context' and\
+                       ident not in self.declared.union(self.locally_declared):
                     self.undeclared.add(ident)
  
 

File mako/exceptions.py

View file
  
 class CompileException(MakoException):
     def __init__(self, message, source, lineno, pos, filename):
-        MakoException.__init__(self, message + _format_filepos(lineno, pos, filename))
+        MakoException.__init__(self,
+                              message + _format_filepos(lineno, pos, filename))
         self.lineno =lineno
         self.pos = pos
         self.filename = filename
  
 class SyntaxException(MakoException):
     def __init__(self, message, source, lineno, pos, filename):
-        MakoException.__init__(self, message + _format_filepos(lineno, pos, filename))
+        MakoException.__init__(self,
+                              message + _format_filepos(lineno, pos, filename))
         self.lineno =lineno
         self.pos = pos
         self.filename = filename
 
 
 try:
-    from mako.ext.pygmentplugin import syntax_highlight, pygments_html_formatter
+    from mako.ext.pygmentplugin import syntax_highlight,\
+            pygments_html_formatter
 except ImportError:
     from mako.filters import html_escape
     pygments_html_formatter = None
     import mako.template
     return mako.template.Template(r"""
 <%!
-    from mako.exceptions import RichTraceback, syntax_highlight, pygments_html_formatter
+    from mako.exceptions import RichTraceback, syntax_highlight,\
+            pygments_html_formatter
 %>
 <%page args="full=True, css=True, error=None, traceback=None"/>
 % if full:
         .stacktrace { margin:5px 5px 5px 5px; }
         .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
         .nonhighlight { padding:0px; background-color:#DFDFDF; }
-        .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; }
+        .sample { padding:10px; margin:10px 10px 10px 10px;
+                  font-family:monospace; }
         .sampleline { padding:0px 10px 0px 10px; }
         .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
         .location { font-size:80%; }
         pre { margin: 0; }
         .syntax-highlighted { padding: 0 10px; }
         .syntax-highlightedtable { border-spacing: 1px; }
-        .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; }
+        .nonhighlight { border-top: 1px solid #DFDFDF;
+                        border-bottom: 1px solid #DFDFDF; }
         .stacktrace .nonhighlight { margin: 5px 15px 10px; }
         .sourceline { margin: 0 0; font-family:monospace; }
         .code { background-color: #F8F8F8; width: 100%; }
 </body>
 </html>
 % endif
-""", output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace')
+""", output_encoding=sys.getdefaultencoding(),
+        encoding_errors='htmlentityreplace')

File mako/ext/pygmentplugin.py

View file
              bygroups(Text, Comment.Preproc, Keyword, Other)),
             (r'(\s*)(\%(?!%))([^\n]*)(\n|\Z)',
              bygroups(Text, Comment.Preproc, using(PythonLexer), Other)),
-             (r'(\s*)(##[^\n]*)(\n|\Z)',
+            (r'(\s*)(##[^\n]*)(\n|\Z)',
               bygroups(Text, Comment.Preproc, Other)),
-              (r'''(?s)<%doc>.*?</%doc>''', Comment.Preproc),
-            (r'(<%)([\w\.\:]+)', bygroups(Comment.Preproc, Name.Builtin), 'tag'),
-            (r'(</%)([\w\.\:]+)(>)', bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)),
+            (r'''(?s)<%doc>.*?</%doc>''', Comment.Preproc),
+            (r'(<%)([\w\.\:]+)',
+              bygroups(Comment.Preproc, Name.Builtin), 'tag'),
+            (r'(</%)([\w\.\:]+)(>)',
+              bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)),
             (r'<%(?=([\w\.\:]+))', Comment.Preproc, 'ondeftags'),
-            (r'(<%(?:!?))(.*?)(%>)(?s)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
+            (r'(<%(?:!?))(.*?)(%>)(?s)',
+              bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
             (r'(\$\{)(.*?)(\})',
              bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
             (r'''(?sx)
                                              **options)
 
 
-pygments_html_formatter = HtmlFormatter(cssclass='syntax-highlighted', linenos=True)
+pygments_html_formatter = HtmlFormatter(cssclass='syntax-highlighted',
+                                        linenos=True)
 def syntax_highlight(filename='', language=None):
     mako_lexer = MakoLexer()
     if util.py3k:
     else:
         python_lexer = PythonLexer()
     if filename.startswith('memory:') or language == 'mako':
-        return lambda string: highlight(string, mako_lexer, pygments_html_formatter)
-    return lambda string: highlight(string, python_lexer, pygments_html_formatter)
+        return lambda string: highlight(string, mako_lexer,
+                                        pygments_html_formatter)
+    return lambda string: highlight(string, python_lexer,
+                                    pygments_html_formatter)
 

File mako/ext/turbogears.py

View file
             return Template(template_string, **self.tmpl_options)
         # Translate TG dot notation to normal / template path
         if '/' not in templatename:
-            templatename = '/' + templatename.replace('.', '/') + '.' + self.extension
+            templatename = '/' + templatename.replace('.', '/') + '.' +\
+                    self.extension
 
         # Lookup template
         return self.lookup.get_template(templatename)

File mako/filters.py

View file
 codecs.register_error('htmlentityreplace', htmlentityreplace_errors)
 
 
-# TODO: options to make this dynamic per-compilation will be added in a later release
+# TODO: options to make this dynamic per-compilation will be added in a later
+# release
 DEFAULT_ESCAPES = {
     'x':'filters.xml_escape',
     'h':'filters.html_escape',

File mako/lexer.py

View file
         return self.match_reg(reg)
  
     def match_reg(self, reg):
-        """match the given regular expression object to the current text position.
+        """match the given regular expression object to the current text
+        position.
  
         if a match occurs, update the current text and line position.
  
             self.lineno += len(lines)
             #print "MATCHED:", match.group(0), "LINE START:", 
             # self.matched_lineno, "LINE END:", self.lineno
-        #print "MATCH:", regexp, "\n", self.text[mp : mp + 15], (match and "TRUE" or "FALSE")
+        #print "MATCH:", regexp, "\n", self.text[mp : mp + 15], \
+        #          (match and "TRUE" or "FALSE")
         return match
  
     def parse_until_text(self, *text):
             match = self.match(r'#.*\n')
             if match:
                 continue
-            match = self.match(r'(\"\"\"|\'\'\'|\"|\')((?<!\\)\\\1|.)*?\1', re.S)
+            match = self.match(r'(\"\"\"|\'\'\'|\"|\')((?<!\\)\\\1|.)*?\1',
+                               re.S)
             if match:
                 continue
             match = self.match(r'(%s)' % text_re)
                     brace_level -= 1
                     continue
                 return \
-                    self.text[startpos:self.match_position-len(match.group(1))],\
+                    self.text[startpos:\
+                              self.match_position-len(match.group(1))],\
                     match.group(1)
             match = self.match(r"(.*?)(?=\"|\'|#|%s)" % text_re, re.S)
             if match:
             elif len(self.control_line) and \
                     not self.control_line[-1].is_ternary(node.keyword):
                 raise exceptions.SyntaxException(
-                                "Keyword '%s' not a legal ternary for keyword '%s'" %
-                                (node.keyword, self.control_line[-1].keyword),
-                                **self.exception_kwargs)
+                          "Keyword '%s' not a legal ternary for keyword '%s'" %
+                          (node.keyword, self.control_line[-1].keyword),
+                          **self.exception_kwargs)
 
     _coding_re = re.compile(r'#.*coding[:=]\s*([-\w.]+).*\r?\n')
 
                 text = text.decode(parsed_encoding)
             except UnicodeDecodeError, e:
                 raise exceptions.CompileException(
-                                "Unicode decode operation of encoding '%s' failed" %
-                                parsed_encoding, 
-                                text.decode('utf-8', 'ignore'), 
-                                0, 0, filename)
+                           "Unicode decode operation of encoding '%s' failed" %
+                           parsed_encoding, 
+                           text.decode('utf-8', 'ignore'), 
+                           0, 0, filename)
 
         return parsed_encoding, text
 
                                                 self.tag[-1].keyword, 
                                                 **self.exception_kwargs)
         if len(self.control_line):
-            raise exceptions.SyntaxException("Unterminated control keyword: '%s'" %
-                                            self.control_line[-1].keyword, 
-                                            self.text, 
-                                            self.control_line[-1].lineno,
-                                            self.control_line[-1].pos, self.filename)
+            raise exceptions.SyntaxException(
+                                      "Unterminated control keyword: '%s'" %
+                                      self.control_line[-1].keyword, 
+                                      self.text, 
+                                      self.control_line[-1].lineno,
+                                      self.control_line[-1].pos, self.filename)
         return self.template
 
     def match_tag_start(self):
  
             ([\w\.\:]+)   # keyword
  
-            ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*)  # attrname, = sign, string expression
+            ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*)  # attrname, = \
+                                               #        sign, string expression
  
             \s*     # more whitespace
  
             re.I | re.S | re.X)
  
         if match:
-            keyword, attr, isend = match.group(1), match.group(2), match.group(3)
+            keyword, attr, isend = match.groups()
+            #keyword, attr, isend = match.group(1), match.group(2),\
+            #                                                    match.group(3)
             self.keyword = keyword
             attributes = {}
             if attr:
-                for att in re.findall(r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr):
+                for att in re.findall(
+                           r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr):
                     key, val1, val2 = att
                     text = val1 or val2
                     text = text.replace('\r\n', '\n')
         if match:
             if not len(self.tag):
                 raise exceptions.SyntaxException(
-                                        "Closing tag without opening tag: </%%%s>" %
-                                        match.group(1), 
-                                        **self.exception_kwargs)
+                                   "Closing tag without opening tag: </%%%s>" %
+                                    match.group(1), 
+                                    **self.exception_kwargs)
             elif self.tag[-1].keyword != match.group(1):
                 raise exceptions.SyntaxException(
-                                        "Closing tag </%%%s> does not match tag: <%%%s>" %
-                                        (match.group(1), self.tag[-1].keyword),
-                                        **self.exception_kwargs)
+                             "Closing tag </%%%s> does not match tag: <%%%s>" %
+                             (match.group(1), self.tag[-1].keyword),
+                             **self.exception_kwargs)
             self.tag.pop()
             return True
         else:
             return False
 
     def match_control_line(self):
-        match = self.match(r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)(?:\r?\n|\Z)", re.M)
+        match = self.match(
+                      r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)"
+                      r"(?:\r?\n|\Z)", re.M)
         if match:
             operator = match.group(1)
             text = match.group(2)

File mako/lookup.py

View file
 
         if uri[0] != '/':
             if relativeto is not None:
-                v = self._uri_cache[key] = posixpath.join(posixpath.dirname(relativeto), uri)
+                v = self._uri_cache[key] = posixpath.join(
+                                            posixpath.dirname(relativeto), uri)
             else:
                 v = self._uri_cache[key] = '/' + uri
         else:

File mako/parsetree.py

View file
             elif key in nonexpressions:
                 if re.search(r'\${.+?}', self.attributes[key]):
                     raise exceptions.CompileException(
-                            "Attibute '%s' in tag '%s' does not allow embedded "
-                            "expressions"  % (key, self.keyword), 
-                            **self.exception_kwargs)
+                           "Attibute '%s' in tag '%s' does not allow embedded "
+                           "expressions"  % (key, self.keyword), 
+                           **self.exception_kwargs)
                 self.parsed_attributes[key] = repr(self.attributes[key])
             else:
                 raise exceptions.CompileException(
         name = attributes.get('name')
         if name and not re.match(r'^[\w_]+$',name):
             raise exceptions.CompileException(
-                                "%block may not specify an argument signature", 
-                                **self.exception_kwargs)
+                               "%block may not specify an argument signature", 
+                               **self.exception_kwargs)
         if not name and attributes.get('args', None):
             raise exceptions.CompileException(
                                 "Only named %blocks may specify args",

File mako/pygen.py

View file
                 # its not a "compound" keyword.  but lets also
                 # test for valid Python keywords that might be indenting us,
                 # else assume its a non-indenting line
-                m2 = re.match(r"^\s*(def|class|else|elif|except|finally)", line)
+                m2 = re.match(r"^\s*(def|class|else|elif|except|finally)",
+                              line)
                 if m2:
                     self.indent += 1
                     self.indent_detail.append(indentor)

File mako/pyparser.py

View file
                 self.listener.codeargs.append(p)
                 self.listener.args.append(ExpressionGenerator(n).value())
                 self.listener.declared_identifiers = \
-                    self.listener.declared_identifiers.union(p.declared_identifiers)
+                    self.listener.declared_identifiers.union(
+                                                      p.declared_identifiers)
                 self.listener.undeclared_identifiers = \
-                    self.listener.undeclared_identifiers.union(p.undeclared_identifiers)
+                    self.listener.undeclared_identifiers.union(
+                                                      p.undeclared_identifiers)
 
         def visit(self, expr):
             visitor.walk(expr, self)  # , walker=walker())

File mako/runtime.py

View file
  
     if not callable(callable_):
         raise exceptions.RuntimeException(
-                            "capture() function expects a callable as "
-                            "its argument (i.e. capture(func, *args, **kwargs))"
+                           "capture() function expects a callable as "
+                           "its argument (i.e. capture(func, *args, **kwargs))"
                         )
     context._push_buffer()
     try:

File mako/util.py

View file
  
     def getvalue(self):
         if self.encoding:
-            return self.delim.join(self.data).encode(self.encoding, self.errors)
+            return self.delim.join(self.data).encode(self.encoding,
+                                                     self.errors)
         else:
             return self.delim.join(self.data)
 
 class LRUCache(dict):
-    """A dictionary-like object that stores a limited number of items, discarding
-    lesser used items periodically.
+    """A dictionary-like object that stores a limited number of items,
+    discarding lesser used items periodically.
  
     this is a rewrite of LRUCache from Myghty to use a periodic timestamp-based
-    paradigm so that synchronization is not really needed.  the size management 
+    paradigm so that synchronization is not really needed.  the size management
     is inexact.
     """
  
                 try:
                     del self[item.key]
                 except KeyError:
-                    # if we couldnt find a key, most likely some other thread broke in 
-                    # on us. loop around and try again
+                    # if we couldn't find a key, most likely some other thread
+                    # broke in on us. loop around and try again
                     break
 
 # Regexp to match python magic encoding line
     re.VERBOSE)
 
 def parse_encoding(fp):
-    """Deduce the encoding of a Python source file (binary mode) from magic comment.
+    """Deduce the encoding of a Python source file (binary mode) from magic
+    comment.
 
     It does this in the same way as the `Python interpreter`__
 
                 pass
             else:
                 line2 = fp.readline()
-                m = _PYTHON_MAGIC_COMMENT_re.match(line2.decode('ascii', 'ignore'))
+                m = _PYTHON_MAGIC_COMMENT_re.match(
+                                               line2.decode('ascii', 'ignore'))
 
         if has_bom:
             if m: