Skip to content

Commit

Permalink
Linting
Browse files Browse the repository at this point in the history
  • Loading branch information
domdfcoding committed Oct 18, 2020
1 parent 23f836a commit 96a1f7d
Show file tree
Hide file tree
Showing 15 changed files with 70 additions and 67 deletions.
2 changes: 1 addition & 1 deletion sphinx_toolbox/more_autodoc/autonamedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def add_content(self, more_content: Any, no_docstring: bool = True):

def _get_docstring(self) -> Tuple[Dict[str, Param], List[str], List[str]]:
"""
Returns params, pre_output, post_output
Returns params, pre_output, post_output.
"""

# Size varies depending on docutils config
Expand Down
6 changes: 4 additions & 2 deletions sphinx_toolbox/more_autodoc/autoprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,10 @@ def filter_members(
# mocked module or object
keep = False

elif self.options.get("exclude-protocol-members",
[]) and membername in self.options["exclude-protocol-members"]:
elif (
self.options.get("exclude-protocol-members", [])
and membername in self.options["exclude-protocol-members"]
):
# remove members given by exclude-protocol-members
keep = False

Expand Down
14 changes: 7 additions & 7 deletions sphinx_toolbox/more_autodoc/generic_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
API Reference
-----------------
"""
""" # noqa: D400
#
# Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
Expand Down Expand Up @@ -74,37 +74,37 @@ class GenericBasesClassDocumenter(PatchedAutoSummClassDocumenter):

def add_directive_header(self, sig: str) -> None:
"""
Add the directive header
Add the directive header.
:param sig:
"""

sourcename = self.get_sourcename()

if self.doc_as_attr:
self.directivetype = 'attribute'
self.directivetype = "attribute"
Documenter.add_directive_header(self, sig)

if self.analyzer and '.'.join(self.objpath) in self.analyzer.finals:
self.add_line(' :final:', sourcename)
self.add_line(" :final:", sourcename)

# add inheritance info, if wanted
if not self.doc_as_attr and self.options.show_inheritance:
self.add_line('', sourcename)
bases = []

if (
hasattr(self.object, '__orig_bases__') and len(self.object.__orig_bases__)
hasattr(self.object, "__orig_bases__") and len(self.object.__orig_bases__)
and get_origin(self.object.__orig_bases__[0]) is self.object.__bases__[0]
):
# Last condition guards against classes that don't directly subclass a Generic.
bases = [format_annotation(b) for b in self.object.__orig_bases__]

elif hasattr(self.object, '__bases__') and len(self.object.__bases__):
elif hasattr(self.object, "__bases__") and len(self.object.__bases__):
bases = [format_annotation(b) for b in self.object.__bases__]

if bases:
self.add_line(' ' + _("Bases: %s") % ', '.join(bases), sourcename)
self.add_line(" " + _("Bases: %s") % ", ".join(bases), sourcename)


def setup(app: Sphinx) -> SphinxExtMetadata:
Expand Down
14 changes: 7 additions & 7 deletions sphinx_toolbox/more_autodoc/overloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def create_body_overloads(self) -> StringList:
for overload in self.analyzer.overloads.get('.'.join(self.objpath)): # type: ignore
overload = self.process_overload_signature(overload)

buf = [format_annotation(self.object), r'\(']
buf = [format_annotation(self.object), r"\("]

for name, param in overload.parameters.items():
buf.append(f"**{name}**")
Expand All @@ -152,7 +152,7 @@ def create_body_overloads(self) -> StringList:
buf.append(" -> ")
buf.append(format_annotation(overload.return_annotation))

formatted_overloads.append("".join(buf))
formatted_overloads.append(''.join(buf))

if len(formatted_overloads) == 1:
output.append(formatted_overloads[0])
Expand Down Expand Up @@ -229,7 +229,7 @@ def process_docstring(
elif line.startswith(":return:") or line.startswith(":returns:"):
insert_index = i - len(lines)

listener_id = self.env.app.connect('autodoc-process-docstring', process_docstring, priority=300)
listener_id = self.env.app.connect("autodoc-process-docstring", process_docstring, priority=300)
super().add_content(more_content, no_docstring)
self.env.app.disconnect(listener_id)

Expand All @@ -246,7 +246,7 @@ class FunctionDocumenter(OverloadMixin, autodoc.FunctionDocumenter):
renders overloads differently.
.. versionadded:: 1.4.0
"""
""" # noqa: D400

def format_signature(self, **kwargs: Any) -> str:
"""
Expand Down Expand Up @@ -310,7 +310,7 @@ def process_overload_signature(self, overload: Signature) -> Signature:
:param overload:
"""

__globals__ = safe_getattr(self.object, '__globals__', {})
__globals__ = safe_getattr(self.object, "__globals__", {})
overload = evaluate_signature(overload, __globals__)
return super().process_overload_signature(overload)

Expand All @@ -321,7 +321,7 @@ class MethodDocumenter(OverloadMixin, autodoc.MethodDocumenter):
renders overloads differently.
.. versionadded:: 1.4.0
"""
""" # noqa: D400

def format_signature(self, **kwargs: Any) -> str:
"""
Expand Down Expand Up @@ -387,7 +387,7 @@ def process_overload_signature(self, overload: Signature) -> Signature:
:param overload:
"""

__globals__ = safe_getattr(self.object, '__globals__', {})
__globals__ = safe_getattr(self.object, "__globals__", {})
overload = evaluate_signature(overload, __globals__)

if not inspect.isstaticmethod(self.object, cls=self.parent, name=self.object_name):
Expand Down
4 changes: 2 additions & 2 deletions sphinx_toolbox/more_autodoc/regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ def copy_asset_files(app: Sphinx, exc):

if exc is None: # build succeeded
with importlib_resources.path(sphinx_toolbox.more_autodoc, "regex.css") as cssfile:
copy_asset(str(pathlib.Path(cssfile)), str(pathlib.Path(app.outdir) / '_static'))
copy_asset(str(pathlib.Path(cssfile)), str(pathlib.Path(app.outdir) / "_static"))


regex_parser = HTMLRegexParser()
Expand All @@ -680,7 +680,7 @@ def setup(app: Sphinx) -> SphinxExtMetadata:
)

app.add_css_file("regex.css")
app.connect('build-finished', copy_asset_files)
app.connect("build-finished", copy_asset_files)

return {
"version": __version__,
Expand Down
6 changes: 3 additions & 3 deletions sphinx_toolbox/more_autodoc/typevars.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,10 @@ class TypeVarDocumenter(VariableDocumenter):
Specialized Documenter subclass for :class:`typing.TypeVars`.
.. versionadded:: 1.3.0
"""
""" # noqa: D400

objtype = 'typevar'
directivetype = 'data'
objtype = "typevar"
directivetype = "data"
priority = DataDocumenter.priority + 1

@classmethod
Expand Down
6 changes: 3 additions & 3 deletions sphinx_toolbox/more_autosummary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,10 @@ def get_documenter(app: Sphinx, obj: Any, parent: Any) -> Type[Documenter]:
else:
parent_doc_cls = ModuleDocumenter

if hasattr(parent, '__name__'):
if hasattr(parent, "__name__"):
parent_doc = parent_doc_cls(FakeDirective(), parent.__name__)
else:
parent_doc = parent_doc_cls(FakeDirective(), "")
parent_doc = parent_doc_cls(FakeDirective(), '')

# Get the correct documenter class for *obj*
classes = [
Expand Down Expand Up @@ -290,7 +290,7 @@ def setup(app: Sphinx) -> SphinxExtMetadata:
app.setup_extension("sphinx.ext.autosummary")
app.setup_extension("autodocsumm")

app.add_directive('autosummary', PatchedAutosummary, override=True)
app.add_directive("autosummary", PatchedAutosummary, override=True)
autodocsumm.AutosummaryDocumenter.add_autosummary = add_autosummary
allow_subclass_add(app, PatchedAutoSummClassDocumenter)

Expand Down
25 changes: 17 additions & 8 deletions sphinx_toolbox/pre_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@
# stdlib
import re
import warnings
from collections import OrderedDict
from textwrap import indent
from typing import List, Sequence
from typing import List, MutableMapping, Sequence, Union

# 3rd party
import ruamel.yaml as yaml
import ruamel.yaml as yaml # type: ignore
from docutils import nodes
from docutils.statemachine import StringList
from domdf_python_tools.paths import PathPlus
Expand All @@ -118,6 +117,12 @@


def parse_hooks(hooks: str) -> List[str]:
"""
Parses the comma, semicolon and/or space delimited list of hook IDs.
:param hooks:
"""

return list(filter(None, re.split("[,; ]", hooks)))


Expand Down Expand Up @@ -151,7 +156,7 @@ def run(self) -> Sequence[nodes.Node]: # type: ignore
return []

repo = make_github_url(self.env.config.github_username, self.env.config.github_repository)
config = {"repo": str(repo)}
config: MutableMapping[str, Union[str, List[MutableMapping[str, str]]]] = {"repo": str(repo)}

if "rev" in self.options:
config["rev"] = self.options["rev"]
Expand All @@ -161,9 +166,11 @@ def run(self) -> Sequence[nodes.Node]: # type: ignore
targetid = f'pre-commit-{self.env.new_serialno("pre-commit"):d}'
targetnode = nodes.section(ids=[targetid])

yaml_output = indent(yaml.round_trip_dump([config], default_flow_style=False), ' ')
content = f".. code-block:: yaml\n\n{yaml_output}\n\n"
yaml_output = yaml.round_trip_dump([config], default_flow_style=False)
if not yaml_output:
return []

content = f".. code-block:: yaml\n\n{indent(yaml_output, ' ')}\n\n"
view = StringList(content.split("\n"))
pre_commit_node = nodes.paragraph(rawsource=content)
self.state.nested_parse(view, self.content_offset, pre_commit_node)
Expand Down Expand Up @@ -202,9 +209,11 @@ def run(self) -> Sequence[nodes.Node]: # type: ignore
targetid = f'pre-commit-{self.env.new_serialno("pre-commit"):d}'
targetnode = nodes.section(ids=[targetid])

yaml_output = indent(yaml.round_trip_dump([config], default_flow_style=False), ' ')
content = f".. code-block:: yaml\n\n{yaml_output}\n\n"
yaml_output = yaml.round_trip_dump([config], default_flow_style=False)
if not yaml_output:
return []

content = f".. code-block:: yaml\n\n{indent(yaml_output, ' ')}\n\n"
view = StringList(content.split("\n"))
pre_commit_node = nodes.paragraph(rawsource=content)
self.state.nested_parse(view, self.content_offset, pre_commit_node)
Expand Down
2 changes: 1 addition & 1 deletion sphinx_toolbox/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,6 @@ def baseclass_is_private(obj: Type) -> bool:
:param obj:
"""

if hasattr(obj, '__bases__') and len(obj.__bases__) == 1:
if hasattr(obj, "__bases__") and len(obj.__bases__) == 1:
return obj.__bases__[0].__name__.startswith("__")
return False
8 changes: 5 additions & 3 deletions tests/overloads_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ def serde(cls: None = None, from_key: str = ..., to_key: str = ...) -> Callable[
... # pragma: no cover


def serde(cls: Optional[Type[object]] = None,
from_key: str = "from",
to_key: str = "to") -> Union[Type[object], Callable[[Type[object]], Type[object]]]:
def serde(
cls: Optional[Type[object]] = None,
from_key: str = "from",
to_key: str = "to",
) -> Union[Type[object], Callable[[Type[object]], Type[object]]]:
r"""
Decorator to add serialisation and deserialisation capabilities to attrs classes.
Expand Down
32 changes: 9 additions & 23 deletions tests/test_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,44 +102,30 @@ class Metaclass(type):
(Any, ":py:data:`~typing.Any`"),
(AnyStr, ":py:data:`~typing.AnyStr`"),
(Mapping, ":py:class:`~typing.Mapping`"),
(Mapping[str, bool], ":py:class:`~typing.Mapping`\\[:py:class:`str`, "
":py:class:`bool`]"),
(Mapping[str, bool], ":py:class:`~typing.Mapping`\\[:py:class:`str`, :py:class:`bool`]"),
(Dict, ":py:class:`~typing.Dict`"),
(Dict[str, bool], ":py:class:`~typing.Dict`\\[:py:class:`str`, "
":py:class:`bool`]"),
(Dict[str, bool], ":py:class:`~typing.Dict`\\[:py:class:`str`, :py:class:`bool`]"),
(Tuple, ":py:data:`~typing.Tuple`"),
(Tuple[str, bool], ":py:data:`~typing.Tuple`\\[:py:class:`str`, "
":py:class:`bool`]"),
(Tuple[str, bool], ":py:data:`~typing.Tuple`\\[:py:class:`str`, :py:class:`bool`]"),
(
Tuple[int, int, int],
":py:data:`~typing.Tuple`\\[:py:class:`int`, "
":py:class:`int`, :py:class:`int`]"
":py:data:`~typing.Tuple`\\[:py:class:`int`, :py:class:`int`, :py:class:`int`]"
),
(Tuple[str, ...], ":py:data:`~typing.Tuple`\\[:py:class:`str`, ...]"),
(Union, ":py:data:`~typing.Union`"),
(Union[str, bool], ":py:data:`~typing.Union`\\[:py:class:`str`, "
":py:class:`bool`]"),
pytest.param(
Union[str, Any],
":py:data:`~typing.Union`\\[:py:class:`str`, "
":py:data:`~typing.Any`]",
marks=pytest.mark.skipif((3, 5, 0) <= sys.version_info[:3] <= (3, 5, 2),
reason="Union erases the str on 3.5.0 -> 3.5.2"),
),
(Union[str, bool], ":py:data:`~typing.Union`\\[:py:class:`str`, :py:class:`bool`]"),
(Union[str, Any], ":py:data:`~typing.Union`\\[:py:class:`str`, :py:data:`~typing.Any`]"),
(Optional[str], ":py:data:`~typing.Optional`\\[:py:class:`str`]"),
(Callable, ":py:data:`~typing.Callable`"),
(Callable[..., int], ":py:data:`~typing.Callable`\\[..., :py:class:`int`]"),
(Callable[[int], int], ":py:data:`~typing.Callable`\\[\\[:py:class:`int`], "
":py:class:`int`]"),
(Callable[[int], int], ":py:data:`~typing.Callable`\\[\\[:py:class:`int`], :py:class:`int`]"),
(
Callable[[int, str], bool],
":py:data:`~typing.Callable`\\[\\[:py:class:`int`, "
":py:class:`str`], :py:class:`bool`]"
":py:data:`~typing.Callable`\\[\\[:py:class:`int`, :py:class:`str`], :py:class:`bool`]"
),
(
Callable[[int, str], None],
":py:data:`~typing.Callable`\\[\\[:py:class:`int`, "
":py:class:`str`], :py:obj:`None`]"
":py:data:`~typing.Callable`\\[\\[:py:class:`int`, :py:class:`str`], :py:obj:`None`]"
),
(Pattern, ":py:class:`~typing.Pattern`"),
(Pattern[str], ":py:class:`~typing.Pattern`\\[:py:class:`str`]"),
Expand Down
6 changes: 3 additions & 3 deletions tests/test_autodoc_variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class Bar:
f: "Set" # type: ignore

def __init__(self):
self.g: Secret = Secret("")
self.h: "Secret" = Secret("")
self.g: Secret = Secret('')
self.h: "Secret" = Secret('')


class Analyzer(NamedTuple):
Expand Down Expand Up @@ -72,4 +72,4 @@ def test_get_variable_type():
Documenter(Bar, ["Bar", "h"], Analyzer({("Bar", "h"): '"Union[str, float, int]"'}))
) == ":py:data:`~typing.Union`\\[:py:class:`str`, :py:class:`float`, :py:class:`int`]"

assert get_variable_type(Documenter('Bar', ["Bar", "f"], Analyzer({}))) == ''
assert get_variable_type(Documenter("Bar", ["Bar", "f"], Analyzer({}))) == ''
2 changes: 1 addition & 1 deletion tests/test_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"regex, expected",
[
(
re.compile(r'(?s)(\.\. start installation)(.*?)(\.\. end installation)'),
re.compile(r"(?s)(\.\. start installation)(.*?)(\.\. end installation)"),
"(.. start installation)(.*?)(.. end installation)",
),
(
Expand Down
6 changes: 3 additions & 3 deletions tests/typevars_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class SlotsDemo:


T = TypeVar("T")
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
S = TypeVar('S', bound=SlotsDemo)
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
S = TypeVar("S", bound=SlotsDemo)
DS = TypeVar("DS", SlotsDemo, Demo)
4 changes: 4 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ rst-roles =
data
py:data
py:exc
deco
regex
rst-directives =
envvar
exception
Expand All @@ -184,6 +186,8 @@ rst-directives =
rst:role
pre-commit-shield
py:data
py:method
py:classmethod
per-file-ignores = tests/*: D100 D101 D102 D103 D104 D106 D201 D204 D207 D208 D209 D210 D211 D212 D213 D214 D215 D300 D301 D400 D402 D403 D404 D415 D417 DALL000
pytest-parametrize-names-type = csv
inline-quotes = "
Expand Down

0 comments on commit 96a1f7d

Please sign in to comment.