ext: pep8 fixes

This commit is contained in:
Georg Brandl 2015-03-08 17:03:00 +01:00
parent ba9dcaac51
commit b5c2279e05
15 changed files with 106 additions and 52 deletions

View File

@ -62,7 +62,9 @@ class DefDict(dict):
return True
__nonzero__ = __bool__ # for python2 compatibility
identity = lambda x: x
def identity(x):
return x
class Options(dict):
@ -1311,9 +1313,9 @@ class AttributeDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter):
isinstance(member, cls.method_types) and not \
type(member).__name__ in ("type", "method_descriptor",
"instancemethod")
return isdatadesc or (not isinstance(parent, ModuleDocumenter)
and not inspect.isroutine(member)
and not isinstance(member, class_types))
return isdatadesc or (not isinstance(parent, ModuleDocumenter) and
not inspect.isroutine(member) and
not isinstance(member, class_types))
def document_members(self, all_members=False):
pass

View File

@ -77,18 +77,20 @@ from sphinx.ext.autodoc import Options
class autosummary_toc(nodes.comment):
pass
def process_autosummary_toc(app, doctree):
"""Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
env = app.builder.env
crawled = {}
def crawl_toc(node, depth=1):
crawled[node] = True
for j, subnode in enumerate(node):
try:
if (isinstance(subnode, autosummary_toc)
and isinstance(subnode[0], addnodes.toctree)):
if (isinstance(subnode, autosummary_toc) and
isinstance(subnode[0], addnodes.toctree)):
env.note_toctree(env.docname, subnode[0])
continue
except IndexError:
@ -99,10 +101,12 @@ def process_autosummary_toc(app, doctree):
crawl_toc(subnode, depth+1)
crawl_toc(doctree)
def autosummary_toc_visit_html(self, node):
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self, node):
pass
@ -112,6 +116,7 @@ def autosummary_noop(self, node):
class autosummary_table(nodes.comment):
pass
def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
@ -134,6 +139,7 @@ class FakeDirective:
env = {}
genopt = Options()
def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
@ -219,7 +225,7 @@ class Autosummary(Directive):
tocnode = addnodes.toctree()
tocnode['includefiles'] = docnames
tocnode['entries'] = [(None, docname) for docname in docnames]
tocnode['entries'] = [(None, docn) for docn in docnames]
tocnode['maxdepth'] = -1
tocnode['glob'] = None
@ -369,6 +375,7 @@ class Autosummary(Directive):
return [table_spec, table]
def mangle_signature(sig, max_chars=30):
"""Reformat a function signature to a more compact form."""
s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()
@ -404,6 +411,7 @@ def mangle_signature(sig, max_chars=30):
return u"(%s)" % sig
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
@ -427,6 +435,7 @@ def limited_join(sep, items, max_chars=30, overflow_marker="..."):
return sep.join(list(items[:n_items]) + [overflow_marker])
# -- Importing items -----------------------------------------------------------
def get_import_prefixes_from_env(env):
@ -449,6 +458,7 @@ def get_import_prefixes_from_env(env):
return prefixes
def import_by_name(name, prefixes=[None]):
"""Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
@ -466,6 +476,7 @@ def import_by_name(name, prefixes=[None]):
tried.append(prefixed_name)
raise ImportError('no module named %s' % ' or '.join(tried))
def _import_by_name(name):
"""Import a Python object given its full name."""
try:

View File

@ -71,12 +71,15 @@ def main(argv=sys.argv):
"." + options.suffix,
template_dir=options.templates)
def _simple_info(msg):
print(msg)
def _simple_warn(msg):
print('WARNING: ' + msg, file=sys.stderr)
# -- Generating output ---------------------------------------------------------
def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',

View File

@ -27,6 +27,7 @@ def write_header(f, text, char='-'):
f.write(text + '\n')
f.write(char * len(text) + '\n')
def compile_regex_list(name, exps, warnfunc):
lst = []
for exp in exps:

View File

@ -15,8 +15,6 @@ import sys
import time
import codecs
from os import path
# circumvent relative import
doctest = __import__('doctest')
from six import itervalues, StringIO, binary_type
from docutils import nodes
@ -29,6 +27,9 @@ from sphinx.util.nodes import set_source_info
from sphinx.util.compat import Directive
from sphinx.util.console import bold
# circumvent relative import
doctest = __import__('doctest')
blankline_re = re.compile(r'^\s*<BLANKLINE>', re.MULTILINE)
doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE)
@ -296,8 +297,8 @@ Doctest summary
if self.config.doctest_test_doctest_blocks:
def condition(node):
return (isinstance(node, (nodes.literal_block, nodes.comment))
and 'testnodetype' in node) or \
return (isinstance(node, (nodes.literal_block, nodes.comment)) and
'testnodetype' in node) or \
isinstance(node, nodes.doctest_block)
else:
def condition(node):

View File

@ -52,10 +52,12 @@ def make_link_role(base_url, prefix):
return [pnode], []
return role
def setup_link_roles(app):
for name, (base_url, prefix) in iteritems(app.config.extlinks):
app.add_role(name, make_link_role(base_url, prefix))
def setup(app):
app.add_config_value('extlinks', {}, 'env')
app.connect('builder-inited', setup_link_roles)

View File

@ -142,8 +142,7 @@ def render_dot(self, code, options, format, prefix='graphviz'):
"""Render graphviz code into a PNG or PDF output file."""
hashkey = (code + str(options) +
str(self.builder.config.graphviz_dot) +
str(self.builder.config.graphviz_dot_args)
).encode('utf-8')
str(self.builder.config.graphviz_dot_args)).encode('utf-8')
fname = '%s-%s.%s' % (prefix, sha1(hashkey).hexdigest(), format)
relfn = posixpath.join(self.builder.imgpath, fname)
@ -284,6 +283,7 @@ def render_dot_texinfo(self, node, code, options, prefix='graphviz'):
self.body.append('@image{%s,,,[graphviz],png}\n' % fname[:-4])
raise nodes.SkipNode
def texinfo_visit_graphviz(self, node):
render_dot_texinfo(self, node, node['code'], node['options'])

View File

@ -27,7 +27,8 @@ from sphinx.util.nodes import set_source_info
from sphinx.util.compat import Directive
class ifconfig(nodes.Element): pass
class ifconfig(nodes.Element):
pass
class IfConfig(Directive):

View File

@ -212,7 +212,7 @@ def load_mappings(app):
cached_vals = list(cache.values())
named_vals = sorted(v for v in cached_vals if v[0])
unnamed_vals = [v for v in cached_vals if not v[0]]
for name, _, invdata in named_vals + unnamed_vals:
for name, _x, invdata in named_vals + unnamed_vals:
if name:
env.intersphinx_named_inventory[name] = invdata
for type, objects in iteritems(invdata):

View File

@ -22,6 +22,7 @@ def html_visit_math(self, node):
self.body.append(self.encode(node['latex']) + '</span>')
raise nodes.SkipNode
def html_visit_displaymath(self, node):
if node['nowrap']:
self.body.append(self.starttag(node, 'div', CLASS='math'))
@ -46,6 +47,7 @@ def html_visit_displaymath(self, node):
self.body.append('</div>\n')
raise nodes.SkipNode
def builder_inited(app):
if not app.config.jsmath_path:
raise ExtensionError('jsmath_path config value must be set for the '

View File

@ -19,9 +19,11 @@ from sphinx.util.compat import Directive
class math(nodes.Inline, nodes.TextElement):
pass
class displaymath(nodes.Part, nodes.Element):
pass
class eqref(nodes.Inline, nodes.TextElement):
pass
@ -46,6 +48,7 @@ def math_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
latex = utils.unescape(text, restore_backslashes=True)
return [math(latex=latex)], []
def eq_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
text = utils.unescape(text)
node = eqref('(?)', '(?)', target=text)
@ -91,6 +94,7 @@ def latex_visit_math(self, node):
self.body.append('\\(' + node['latex'] + '\\)')
raise nodes.SkipNode
def latex_visit_displaymath(self, node):
if node['nowrap']:
self.body.append(node['latex'])
@ -99,6 +103,7 @@ def latex_visit_displaymath(self, node):
self.body.append(wrap_displaymath(node['latex'], label))
raise nodes.SkipNode
def latex_visit_eqref(self, node):
self.body.append('\\eqref{%s-%s}' % (node['docname'], node['target']))
raise nodes.SkipNode
@ -108,12 +113,14 @@ def text_visit_math(self, node):
self.add_text(node['latex'])
raise nodes.SkipNode
def text_visit_displaymath(self, node):
self.new_state()
self.add_text(node['latex'])
self.end_state()
raise nodes.SkipNode
def text_visit_eqref(self, node):
self.add_text(node['target'])
raise nodes.SkipNode
@ -123,11 +130,15 @@ def man_visit_math(self, node):
self.body.append(node['latex'])
raise nodes.SkipNode
def man_visit_displaymath(self, node):
self.visit_centered(node)
def man_depart_displaymath(self, node):
self.depart_centered(node)
def man_visit_eqref(self, node):
self.body.append(node['target'])
raise nodes.SkipNode
@ -137,14 +148,18 @@ def texinfo_visit_math(self, node):
self.body.append('@math{' + self.escape_arg(node['latex']) + '}')
raise nodes.SkipNode
def texinfo_visit_displaymath(self, node):
if node.get('label'):
self.add_anchor(node['label'], node)
self.body.append('\n\n@example\n%s\n@end example\n\n' %
self.escape_arg(node['latex']))
def texinfo_depart_displaymath(self, node):
pass
def texinfo_visit_eqref(self, node):
self.add_xref(node['docname'] + ':' + node['target'],
node['target'], node)
@ -154,6 +169,7 @@ def texinfo_visit_eqref(self, node):
def html_visit_eqref(self, node):
self.body.append('<a href="#equation-%s">' % node['target'])
def html_depart_eqref(self, node):
self.body.append('</a>')

View File

@ -25,6 +25,7 @@ def html_visit_math(self, node):
self.builder.config.mathjax_inline[1] + '</span>')
raise nodes.SkipNode
def html_visit_displaymath(self, node):
self.body.append(self.starttag(node, 'div', CLASS='math'))
if node['nowrap']:
@ -52,6 +53,7 @@ def html_visit_displaymath(self, node):
self.body.append('</div>\n')
raise nodes.SkipNode
def builder_inited(app):
if not app.config.mathjax_path:
raise ExtensionError('mathjax_path config value must be set for the '

View File

@ -28,6 +28,7 @@ from sphinx.util.osutil import ensuredir, ENOENT, cd
from sphinx.util.pycompat import sys_encoding
from sphinx.ext.mathbase import setup_math as mathbase_setup, wrap_displaymath
class MathExtError(SphinxError):
category = 'Math extension error'
@ -67,6 +68,7 @@ DOC_BODY_PREVIEW = r'''
depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]')
def render_math(self, math):
"""Render the LaTeX math expression *math* using latex and dvipng.
@ -166,6 +168,7 @@ def render_math(self, math):
return relfn, depth
def cleanup_tempdir(app, exc):
if exc:
return
@ -176,11 +179,13 @@ def cleanup_tempdir(app, exc):
except Exception:
pass
def get_tooltip(self, node):
if self.builder.config.pngmath_add_tooltips:
return ' alt="%s"' % self.encode(node['latex']).strip()
return ''
def html_visit_math(self, node):
try:
fname, depth = render_math(self, '$'+node['latex']+'$')
@ -202,6 +207,7 @@ def html_visit_math(self, node):
self.body.append(c + '/>')
raise nodes.SkipNode
def html_visit_displaymath(self, node):
if node['nowrap']:
latex = node['latex']
@ -224,8 +230,8 @@ def html_visit_displaymath(self, node):
self.body.append('<span class="math">%s</span></p>\n</div>' %
self.encode(node['latex']).strip())
else:
self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node)
+ '/></p>\n</div>')
self.body.append(('<img src="%s"' % fname) + get_tooltip(self, node) +
'/></p>\n</div>')
raise nodes.SkipNode

View File

@ -20,8 +20,13 @@ from sphinx.environment import NoUri
from sphinx.util.nodes import set_source_info
from sphinx.util.compat import Directive, make_admonition
class todo_node(nodes.Admonition, nodes.Element): pass
class todolist(nodes.General, nodes.Element): pass
class todo_node(nodes.Admonition, nodes.Element):
pass
class todolist(nodes.General, nodes.Element):
pass
class Todo(Directive):
@ -161,9 +166,11 @@ def merge_info(app, env, docnames, other):
def visit_todo_node(self, node):
self.visit_admonition(node)
def depart_todo_node(self, node):
self.depart_admonition(node)
def setup(app):
app.add_config_value('todo_include_todos', False, 'html')

View File

@ -155,8 +155,8 @@ def collect_pages(app):
backlink = urito(pagename, docname) + '#' + refname + '.' + name
lines[start] = (
'<div class="viewcode-block" id="%s"><a class="viewcode-back" '
'href="%s">%s</a>' % (name, backlink, _('[docs]'))
+ lines[start])
'href="%s">%s</a>' % (name, backlink, _('[docs]')) +
lines[start])
lines[min(end - 1, maxindex)] += '</div>'
# try to find parents (for submodules)
parents = []