1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
|
#!/usr/bin/env python3
#
# autonamedtuple.py
r"""
A Sphinx directive for documenting :class:`NamedTuples <typing.NamedTuple>` in Python.
.. versionadded:: 0.8.0
.. extensions:: sphinx_toolbox.more_autodoc.autonamedtuple
.. versionchanged:: 1.5.0
``__new__`` methods are documented regardless of other exclusion settings
if the annotations differ from the namedtuple itself.
Usage
---------
.. rst:directive:: autonamedtuple
Directive to automatically document a :class:`typing.NamedTuple` or :func:`collections.namedtuple`.
The output is based on the :rst:dir:`autoclass` directive.
The list of parameters and the attributes are replaced by a list of Fields,
combining the types and docstrings from the class docstring individual attributes.
These will always be shown regardless of the state of the ``:members:`` option.
Otherwise the directive behaves the same as :rst:dir:`autoclass`, and takes all of its arguments.
See https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html for further information.
.. versionadded:: 0.8.0
.. rst:role:: namedtuple
Role which provides a cross-reference to the documentation generated by :rst:dir:`autonamedtuple`.
.. rst:role:: namedtuple-field
Role which provides a cross-reference to a field in the namedtuple documentation.
.. versionadded:: 3.0.0
.. note::
Due to limitations in docutils cross-references for all fields in a namedtuple
will point to the top of the fields list, rather than the individial fields.
.. seealso:: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
:bold-title:`Examples`
.. literalinclude:: ../../../autonamedtuple_demo.py
:language: python
:tab-width: 4
:linenos:
:lines: 1-59
.. rest-example::
.. automodule:: autonamedtuple_demo
:no-autosummary:
:exclude-members: Movie
.. autonamedtuple:: autonamedtuple_demo.Movie
This function takes a single argument, the :namedtuple:`~.Movie` to watch.
The name of the movie can be accessed with the :namedtuple-field:`~.Movie.name` attribute.
API Reference
---------------
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# Parts based on https://github.com/sphinx-doc/sphinx
# | Copyright (c) 2007-2020 by the Sphinx team (see AUTHORS file).
# | BSD Licensed
# | All rights reserved.
# |
# | Redistribution and use in source and binary forms, with or without
# | modification, are permitted provided that the following conditions are
# | met:
# |
# | * Redistributions of source code must retain the above copyright
# | notice, this list of conditions and the following disclaimer.
# |
# | * Redistributions in binary form must reproduce the above copyright
# | notice, this list of conditions and the following disclaimer in the
# | documentation and/or other materials provided with the distribution.
# |
# | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# stdlib
import inspect
import re
import sys
import textwrap
from textwrap import dedent
from typing import Any, Dict, List, Optional, Tuple, Type, cast, get_type_hints
# 3rd party
from docutils import nodes
from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.domains import ObjType
from sphinx.domains.python import PyAttribute, PyClasslike, PythonDomain, PyXRefRole
from sphinx.ext.autodoc import ClassDocumenter, Documenter, Options
from sphinx.ext.autodoc.directive import DocumenterBridge
from sphinx.locale import _
from sphinx.pycode import ModuleAnalyzer
from sphinx.util.nodes import make_id
# this package
from sphinx_toolbox.more_autodoc import ObjectMembers, _documenter_add_content
from sphinx_toolbox.more_autodoc.typehints import format_annotation
from sphinx_toolbox.utils import (
Param,
SphinxExtMetadata,
add_fallback_css_class,
add_nbsp_substitution,
allow_subclass_add,
baseclass_is_private,
is_namedtuple,
metadata_add_version,
parse_parameters
)
__all__ = ("NamedTupleDocumenter", "setup")
class NamedTupleDocumenter(ClassDocumenter):
r"""
Sphinx autodoc :class:`~sphinx.ext.autodoc.Documenter`
for documenting :class:`typing.NamedTuple`\s.
.. versionadded:: 0.8.0
.. versionchanged:: 0.1.0
Will no longer attempt to find attribute docstrings from other namedtuple classes.
""" # noqa: D400
objtype = "namedtuple"
directivetype = "namedtuple"
priority = 20
object: Type # noqa: A003 # pylint: disable=redefined-builtin
field_alias_re = re.compile("Alias for field number [0-9]+")
def __init__(self, directive: DocumenterBridge, name: str, indent: str = '') -> None:
super().__init__(directive, name, indent)
self.options = Options(self.options.copy())
@classmethod
def can_document_member(
cls,
member: Any,
membername: str,
isattr: bool,
parent: Any,
) -> bool:
"""
Called to see if a member can be documented by this documenter.
:param member: The member being checked.
:param membername: The name of the member.
:param isattr:
:param parent: The parent of the member.
"""
return is_namedtuple(member)
def add_content(self, more_content: Optional[StringList], no_docstring: bool = True) -> None:
r"""
Add extra content (from docstrings, attribute docs etc.),
but not the :class:`typing.NamedTuple`\'s docstring.
:param more_content:
:param no_docstring:
""" # noqa: D400
_documenter_add_content(self, more_content, True)
# set sourcename and add content from attribute documentation
sourcename = self.get_sourcename()
params, pre_output, post_output = self._get_docstring()
for line in pre_output:
self.add_line(line, sourcename)
def _get_docstring(self) -> Tuple[Dict[str, Param], List[str], List[str]]:
"""
Returns params, pre_output, post_output.
"""
# Size varies depending on docutils config
tab_size = self.env.app.config.docutils_tab_width
if self.object.__doc__:
docstring = dedent(self.object.__doc__).expandtabs(tab_size).split('\n')
elif "show-inheritance" not in self.options:
docstring = [":class:`typing.NamedTuple`."]
else:
docstring = [''] # pylint: disable=W8301
docstring = list(self.process_doc([docstring]))
return parse_parameters(docstring, tab_size=tab_size)
def add_directive_header(self, sig: str) -> None:
"""
Add the directive's header, and the inheritance information if the ``:show-inheritance:`` flag set.
:param sig: The NamedTuple's signature.
"""
super().add_directive_header(sig)
if "show-inheritance" not in self.options:
return
acceptable_bases = {
" Bases: :class:`tuple`",
" Bases: :py:class:`tuple`",
" Bases: :class:`tuple`, :class:`typing.Generic`",
" Bases: :py:class:`tuple`, :py:class:`typing.Generic`",
" Bases: :class:`NamedTuple`",
" Bases: :py:class:`NamedTuple`",
}
# TODO: support generic bases for multiple inheritance
if self.directive.result[-1] in acceptable_bases or baseclass_is_private(self.object):
# TODO: multiple inheritance
if getattr(self.env.config, "generic_bases_fully_qualified", False):
# Might not be present; extension might not be enabled
prefix = ''
else:
prefix = '~'
if hasattr(self.object, "__annotations__"):
self.directive.result[-1] = f" Bases: :class:`{prefix}typing.NamedTuple`"
else:
self.directive.result[-1] = f" Bases: :func:`{prefix}collections.namedtuple`"
def filter_members(
self,
members: ObjectMembers,
want_all: bool,
) -> List[Tuple[str, Any, bool]]:
"""
Filter the list of members to always include ``__new__`` if it has a different signature to the tuple.
:param members:
:param want_all:
"""
all_hints = get_type_hints(self.object)
class_hints = {k: all_hints[k] for k in self.object._fields if k in all_hints}
# TODO: need a better way to partially resolve type hints, and warn about failures
new_hints = get_type_hints(
self.object.__new__,
globalns=sys.modules[self.object.__module__].__dict__,
localns=self.object.__dict__, # type: ignore[arg-type]
)
# Stock NamedTuples don't have these, but customised collections.namedtuple or hand-rolled classes may
if "cls" in new_hints:
new_hints.pop("cls")
if "return" in new_hints:
new_hints.pop("return")
if class_hints and new_hints and class_hints != new_hints:
#: __new__ has a different signature or different annotations
def unskip_new(app, what, name, obj, skip, options) -> Optional[bool]: # noqa: MAN001
if name == "__new__":
return False
return None
listener_id = self.env.app.connect("autodoc-skip-member", unskip_new)
members_ = super().filter_members(members, want_all)
self.env.app.disconnect(listener_id)
return members_
else:
return super().filter_members(members, want_all)
def sort_members(
self,
documenters: List[Tuple[Documenter, bool]],
order: str,
) -> List[Tuple[Documenter, bool]]:
r"""
Sort the :class:`typing.NamedTuple`\'s members.
:param documenters:
:param order:
"""
# The documenters for the fields and methods, in the desired order
# The fields will be in bysource order regardless of the order option
documenters = super().sort_members(documenters, order)
# Size varies depending on docutils config
a_tab = ' ' * self.env.app.config.docutils_tab_width
# Mapping of member names to docstrings (as list of strings)
member_docstrings: Dict[str, List[str]]
try:
namedtuple_source = textwrap.dedent(inspect.getsource(self.object))
# Mapping of member names to docstrings (as list of strings)
member_docstrings = {
k[1]: v
for k,
v in ModuleAnalyzer.for_string(namedtuple_source, self.object.__module__
).find_attr_docs().items()
}
except (TypeError, OSError):
member_docstrings = {}
# set sourcename and add content from attribute documentation
sourcename = self.get_sourcename()
params, pre_output, post_output = self._get_docstring()
self.add_line('', sourcename)
self.add_line(":Fields:", sourcename)
# TODO: support for default_values
self.add_line('', sourcename)
fields = self.object._fields
fields_body = []
for pos, field in enumerate(fields):
doc: List[str] = [''] # pylint: disable=W8201
arg_type: str = ''
# Prefer doc from class docstring
if field in params:
doc, arg_type = params.pop(field).values() # type: ignore[assignment]
# Otherwise use attribute docstring
if not ''.join(doc).strip() and field in member_docstrings:
doc = member_docstrings[field]
# Fallback to namedtuple's default docstring
if not ''.join(doc).strip():
doc = [getattr(self.object, field).__doc__] # pylint: disable=W8301
# Prefer annotations over docstring types
type_hints = get_type_hints(self.object)
if type_hints:
if field in type_hints:
arg_type = format_annotation(type_hints[field])
self.add_line(f"{a_tab}.. namedtuple-field:: {field}", sourcename)
self.add_line('', sourcename)
# field_entry = [f"{a_tab}{pos})", "|nbsp|", f"**{field}**"]
field_entry = [f"{a_tab}{pos}) \u00A0**{field}**"]
if arg_type:
field_entry.append(f"({arg_type}\\)")
field_entry.append("--")
field_entry.extend(doc)
if self.field_alias_re.match(getattr(self.object, field).__doc__ or ''):
getattr(self.object, field).__doc__ = ' '.join(doc)
fields_body.append(' '.join(field_entry))
fields_body.append('')
for line in fields_body:
self.add_line(line, sourcename)
self.add_line('', sourcename)
for line in post_output:
self.add_line(line, sourcename)
self.add_line('', sourcename)
# Stop a duplicate set of parameters being added with `autodoc_typehints = 'both'`
self.env.temp_data["annotations"] = {}
# Remove documenters corresponding to fields and return the rest
return [d for d in documenters if d[0].name.split('.')[-1] not in fields]
class _PyNamedTuplelike(PyClasslike):
"""
Description of a namedtuple-like object.
"""
def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:
if self.objtype == "namedtuple":
return _("%s (namedtuple in %s)") % (name_cls[0], modname)
else:
return super().get_index_text(modname, name_cls)
class _PyNamedTupleField(PyAttribute):
"""
Index entry and target for a namedtuple field.
"""
def run(self) -> List[nodes.Node]:
if ':' in self.name:
self.domain, self.objtype = self.name.split(':', 1)
else:
self.domain, self.objtype = '', self.name
self.indexnode = addnodes.index(entries=[])
modname = self.options.get("module", self.env.ref_context.get("py:module"))
classname = self.env.ref_context.get("py:class")
name = self.arguments[0]
full_name = f"{classname}.{name}"
fullname = (modname + '.' if modname else '') + full_name
node_id = make_id(self.env, self.state.document, '', fullname)
node = nodes.target('', '', ids=[node_id])
node.document = self.state.document
node.attributes["namedtuple_field"] = True
if "noindex" not in self.options:
# only add target and index entry if this is the first
# description of the object with this name in this desc block
domain = cast(PythonDomain, self.env.get_domain("py"))
domain.note_object(fullname, self.objtype, node_id, location=node)
if "noindexentry" not in self.options:
key = name[0].upper()
pair = [ # pylint: disable=W8301
_("%s (namedtuple in %s)") % (classname, modname),
_("%s (namedtuple field)") % name,
]
self.indexnode["entries"].append(("pair", "; ".join(pair), node_id, '', key))
return [self.indexnode, node]
def _patch_reorder_transform():
# Patch ReorderConsecutiveTargetAndIndexNodes on Sphinx 7.2+
# 3rd party
import sphinx.transforms
if sphinx.version_info >= (7, 2):
orig_reorder_func = sphinx.transforms._reorder_index_target_nodes # type: ignore[attr-defined]
def _reorder_index_target_nodes(start_node: nodes.target) -> None:
if start_node.attributes.get("namedtuple_field", False):
return
orig_reorder_func(start_node)
sphinx.transforms._reorder_index_target_nodes = _reorder_index_target_nodes # type: ignore[attr-defined]
@metadata_add_version
def setup(app: Sphinx) -> SphinxExtMetadata:
"""
Setup :mod:`sphinx_toolbox.more_autodoc.autonamedtuple`.
.. versionadded:: 0.8.0
:param app: The Sphinx application.
"""
# Hack to get the docutils tab size, as there doesn't appear to be any other way
app.setup_extension("sphinx_toolbox.tweaks.tabsize")
app.registry.domains["py"].object_types["namedtuple"] = ObjType(_("namedtuple"), "namedtuple", "class", "obj")
app.add_directive_to_domain("py", "namedtuple", _PyNamedTuplelike)
app.add_role_to_domain("py", "namedtuple", PyXRefRole())
app.add_directive_to_domain("py", "namedtuple-field", _PyNamedTupleField)
app.add_role_to_domain("py", "namedtuple-field", PyXRefRole())
app.registry.domains["py"].object_types["namedtuple-field"] = ObjType(
_("namedtuple-field"),
"namedtuple-field",
"attr",
"obj",
)
app.connect("object-description-transform", add_fallback_css_class({"namedtuple": "class"}))
allow_subclass_add(app, NamedTupleDocumenter)
app.connect("config-inited", lambda _, config: add_nbsp_substitution(config))
_patch_reorder_transform()
return {"parallel_read_safe": True}
|