aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenjamin Trofatter <bentrofatter@gmail.com>2012-03-24 18:43:15 -0500
committerBenjamin Trofatter <bentrofatter@gmail.com>2012-03-24 18:43:15 -0500
commit4b395f679029b8375063e4408ca08a7a860cb99c (patch)
treef408b56e4fcfe12a47be5d2200f3a659db8ef097
parentf7983ce165440bdaeac4d544f393fc76d8ce4cf0 (diff)
downloadexternal_python_mako-4b395f679029b8375063e4408ca08a7a860cb99c.tar.gz
external_python_mako-4b395f679029b8375063e4408ca08a7a860cb99c.tar.bz2
external_python_mako-4b395f679029b8375063e4408ca08a7a860cb99c.zip
Brought all modules into PEP 8 width compliance
-rw-r--r--mako/ast.py26
-rw-r--r--mako/cache.py8
-rw-r--r--mako/codegen.py189
-rw-r--r--mako/exceptions.py21
-rw-r--r--mako/ext/pygmentplugin.py22
-rw-r--r--mako/ext/turbogears.py3
-rw-r--r--mako/filters.py3
-rw-r--r--mako/lexer.py63
-rw-r--r--mako/lookup.py3
-rw-r--r--mako/parsetree.py10
-rw-r--r--mako/pygen.py3
-rw-r--r--mako/pyparser.py6
-rw-r--r--mako/runtime.py4
-rw-r--r--mako/util.py19
14 files changed, 231 insertions, 149 deletions
diff --git a/mako/ast.py b/mako/ast.py
index f2f09d6..d6fa215 100644
--- a/mako/ast.py
+++ b/mako/ast.py
@@ -15,13 +15,16 @@ class PythonCode(object):
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:
@@ -58,7 +61,8 @@ class ArgumentList(object):
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:
@@ -70,8 +74,8 @@ class PythonFragment(PythonCode):
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)
@@ -102,15 +106,16 @@ class FunctionDecl(object):
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]
@@ -142,4 +147,5 @@ class FunctionArgs(FunctionDecl):
"""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)
diff --git a/mako/cache.py b/mako/cache.py
index 959640e..7dcc3f8 100644
--- a/mako/cache.py
+++ b/mako/cache.py
@@ -128,13 +128,17 @@ class Cache(object):
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)
diff --git a/mako/codegen.py b/mako/codegen.py
index c5e94c0..c8da0c7 100644
--- a/mako/codegen.py
+++ b/mako/codegen.py
@@ -4,7 +4,8 @@
# 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
@@ -228,7 +229,8 @@ class _GenerateRenderMethod(object):
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."""
@@ -236,7 +238,8 @@ class _GenerateRenderMethod(object):
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)),
@@ -247,7 +250,8 @@ class _GenerateRenderMethod(object):
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')
@@ -326,7 +330,8 @@ class _GenerateRenderMethod(object):
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)
@@ -343,27 +348,32 @@ class _GenerateRenderMethod(object):
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,
@@ -373,7 +383,8 @@ class _GenerateRenderMethod(object):
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")
@@ -408,7 +419,8 @@ class _GenerateRenderMethod(object):
# 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
@@ -435,7 +447,8 @@ class _GenerateRenderMethod(object):
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'])
@@ -481,7 +494,7 @@ class _GenerateRenderMethod(object):
)
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:
@@ -501,7 +514,8 @@ class _GenerateRenderMethod(object):
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
@@ -519,7 +533,8 @@ class _GenerateRenderMethod(object):
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):
@@ -529,8 +544,10 @@ class _GenerateRenderMethod(object):
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'))
@@ -560,12 +577,15 @@ class _GenerateRenderMethod(object):
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 ''")
@@ -588,8 +608,8 @@ class _GenerateRenderMethod(object):
)
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:
@@ -597,10 +617,12 @@ class _GenerateRenderMethod(object):
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:
@@ -616,7 +638,8 @@ class _GenerateRenderMethod(object):
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:
@@ -652,24 +675,26 @@ class _GenerateRenderMethod(object):
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
)
@@ -717,7 +742,8 @@ class _GenerateRenderMethod(object):
) 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)
@@ -776,20 +802,21 @@ class _GenerateRenderMethod(object):
# 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)" %
@@ -808,9 +835,10 @@ class _GenerateRenderMethod(object):
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):
@@ -842,8 +870,8 @@ class _GenerateRenderMethod(object):
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]
@@ -880,11 +908,13 @@ class _GenerateRenderMethod(object):
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
@@ -904,9 +934,9 @@ class _Identifiers(object):
# 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
@@ -949,7 +979,8 @@ class _Identifiers(object):
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" %
@@ -968,7 +999,8 @@ class _Identifiers(object):
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),
@@ -982,7 +1014,8 @@ class _Identifiers(object):
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)
@@ -1001,7 +1034,8 @@ class _Identifiers(object):
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
@@ -1029,7 +1063,8 @@ class _Identifiers(object):
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
@@ -1048,13 +1083,15 @@ class _Identifiers(object):
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:
@@ -1081,7 +1118,8 @@ class _Identifiers(object):
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)
@@ -1089,7 +1127,8 @@ class _Identifiers(object):
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)
diff --git a/mako/exceptions.py b/mako/exceptions.py
index abb866e..9bc706d 100644
--- a/mako/exceptions.py
+++ b/mako/exceptions.py
@@ -24,7 +24,8 @@ def _format_filepos(lineno, pos, filename):
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
@@ -32,7 +33,8 @@ class CompileException(MakoException):
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
@@ -232,7 +234,8 @@ ${tback.errorname}: ${tback.message}
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
@@ -254,7 +257,8 @@ def html_error_template():
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:
@@ -268,7 +272,8 @@ def html_error_template():
.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%; }
@@ -281,7 +286,8 @@ def html_error_template():
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%; }
@@ -352,4 +358,5 @@ def html_error_template():
</body>
</html>
% endif
-""", output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace')
+""", output_encoding=sys.getdefaultencoding(),
+ encoding_errors='htmlentityreplace')
diff --git a/mako/ext/pygmentplugin.py b/mako/ext/pygmentplugin.py
index 98e0c5d..773f47a 100644
--- a/mako/ext/pygmentplugin.py
+++ b/mako/ext/pygmentplugin.py
@@ -26,13 +26,16 @@ class MakoLexer(RegexLexer):
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)
@@ -103,7 +106,8 @@ class MakoCssLexer(DelegatingLexer):
**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:
@@ -111,6 +115,8 @@ def syntax_highlight(filename='', language=None):
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)
diff --git a/mako/ext/turbogears.py b/mako/ext/turbogears.py
index 94e300a..e453ada 100644
--- a/mako/ext/turbogears.py
+++ b/mako/ext/turbogears.py
@@ -39,7 +39,8 @@ class TGPlugin(object):
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)
diff --git a/mako/filters.py b/mako/filters.py
index a9902df..514daf0 100644
--- a/mako/filters.py
+++ b/mako/filters.py
@@ -165,7 +165,8 @@ def htmlentityreplace_errors(ex):
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',
diff --git a/mako/lexer.py b/mako/lexer.py
index 8c8b849..38ddabf 100644
--- a/mako/lexer.py
+++ b/mako/lexer.py
@@ -62,7 +62,8 @@ class Lexer(object):
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.
@@ -86,7 +87,8 @@ class Lexer(object):
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):
@@ -97,7 +99,8 @@ class Lexer(object):
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)
@@ -106,7 +109,8 @@ class Lexer(object):
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:
@@ -144,9 +148,9 @@ class Lexer(object):
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')
@@ -183,10 +187,10 @@ class Lexer(object):
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
@@ -235,11 +239,12 @@ class Lexer(object):
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):
@@ -248,7 +253,8 @@ class Lexer(object):
([\w\.\:]+) # keyword
- ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*) # attrname, = sign, string expression
+ ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*) # attrname, = \
+ # sign, string expression
\s* # more whitespace
@@ -259,11 +265,14 @@ class Lexer(object):
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')
@@ -290,14 +299,14 @@ class Lexer(object):
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:
@@ -377,7 +386,9 @@ class Lexer(object):
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)
diff --git a/mako/lookup.py b/mako/lookup.py
index f6f811b..b0d67d4 100644
--- a/mako/lookup.py
+++ b/mako/lookup.py
@@ -245,7 +245,8 @@ class TemplateLookup(TemplateCollection):
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:
diff --git a/mako/parsetree.py b/mako/parsetree.py
index c3aa688..2425931 100644
--- a/mako/parsetree.py
+++ b/mako/parsetree.py
@@ -307,9 +307,9 @@ class Tag(Node):
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(
@@ -464,8 +464,8 @@ class BlockTag(Tag):
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",
diff --git a/mako/pygen.py b/mako/pygen.py
index 6b1767c..76e7f6a 100644
--- a/mako/pygen.py
+++ b/mako/pygen.py
@@ -116,7 +116,8 @@ class PythonPrinter(object):
# 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)
diff --git a/mako/pyparser.py b/mako/pyparser.py
index 1fc2c5d..cd7d04f 100644
--- a/mako/pyparser.py
+++ b/mako/pyparser.py
@@ -333,9 +333,11 @@ else:
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())
diff --git a/mako/runtime.py b/mako/runtime.py
index 5a83a81..9101af3 100644
--- a/mako/runtime.py
+++ b/mako/runtime.py
@@ -645,8 +645,8 @@ def capture(context, callable_, *args, **kwargs):
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:
diff --git a/mako/util.py b/mako/util.py
index ce0bab8..3f33ba3 100644
--- a/mako/util.py
+++ b/mako/util.py
@@ -187,16 +187,17 @@ class FastEncodingBuffer(object):
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.
"""
@@ -244,8 +245,8 @@ class LRUCache(dict):
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
@@ -254,7 +255,8 @@ _PYTHON_MAGIC_COMMENT_re = re.compile(
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`__
@@ -283,7 +285,8 @@ def parse_encoding(fp):
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: