pyTooling.Documentation.Sphinx.Directives

A base-class for Sphinx directives, wrapping the parts of docutils a directive keeps re-deriving.

Sphinx and docutils present their options as an untyped mapping and their tables as a tree of nodes assembled by hand. BaseDirective puts a typed, validating layer over both: an option is read with a method that returns the type asked for and raises SphinxExtensionError naming the directive and the option when it can’t, and a table header is described by its columns rather than built node by node.

See also

pyTooling.Documentation.Sphinx

→ The extension this belongs to, and what else it brings.

Functions

  • strip(): Option converter removing surrounding whitespace.

  • stripAndNormalize(): Option converter removing surrounding whitespace and lowering the case.

Exceptions

Classes

  • BaseDirective: Base-class for a directive, offering typed option access and table construction.


Functions

pyTooling.Documentation.Sphinx.Directives.strip(option)[source]

Option converter removing surrounding whitespace.

Parameters:

option (str) – The option’s value as it was written.

Return type:

str

Returns:

The value without surrounding whitespace.

pyTooling.Documentation.Sphinx.Directives.stripAndNormalize(option)[source]

Option converter removing surrounding whitespace and lowering the case.

Parameters:

option (str) – The option’s value as it was written.

Return type:

str

Returns:

The value without surrounding whitespace, in lower case.


Exceptions

exception pyTooling.Documentation.Sphinx.Directives.SphinxExtensionError[source]

Base-exception of all exceptions raised by pyTooling.Documentation.Sphinx.

It derives from both hierarchies on purpose: ExtensionError is what Sphinx catches and reports with the position of the directive, and DocumentationError is what a caller of pyTooling catches. Neither would be enough alone.

Inheritance

Inheritance diagram of SphinxExtensionError

__init__(message, orig_exc=None, modname=None)
Parameters:
Return type:

None

classmethod __new__(*args, **kwargs)

Classes

class pyTooling.Documentation.Sphinx.Directives.BaseDirective[source]

Base-class for a directive, offering typed option access and table construction.

A derived class sets directiveName - which is what the error messages name - and declares option_spec as any directive does. What it gets in return is a _Parse***Option per type instead of reaching into options and validating by hand, and a _Create***TableHeader per table shape instead of assembling tgroup, colspec, thead and row in the right order.

Inheritance

Inheritance diagram of BaseDirective

has_content = False

A boolean; True if content is allowed.

required_arguments = 0

Number of required directive arguments.

optional_arguments = 0

Number of optional arguments after the required ones.

final_argument_whitespace = False

A boolean; True if the last argument may contain spaces.

option_spec: ClassVar[OptionSpec] = {}

Mapping of option names to validator functions.

directiveName: str

Name the directive is invoked by, used in every error message.

_ParseBooleanOption(optionName, default=None)[source]

Read an option written as yes/true or no/false.

Parameters:
  • optionName (str) – Name of the option to read.

  • default (bool | None) – Optional, the value to return when the option wasn’t given.

Return type:

bool

Returns:

The option’s value.

Raises:
_ParseStringOption(optionName, default=None, regexp='\\\\w+')[source]

Read an option that has to match a regular expression.

The pattern defaults to one or more word characters.

Parameters:
  • optionName (str) – Name of the option to read.

  • default (str | None) – Optional, the value to return when the option wasn’t given.

  • regexp (str) – Optional, the pattern the value has to match.

Return type:

str

Returns:

The option’s value.

Raises:
_ParseEnumOption(optionName, enumType, default=None)[source]

Read an option naming a member of an enumeration.

The written value is lowered and its dashes become underscores, so horizontal-table in a document selects the horizontal_table member - a document reads in the spelling documents use, and the enumeration keeps the spelling Python uses.

Parameters:
  • optionName (str) – Name of the option to read.

  • enumType (type[TypeVar(_EnumType, bound= Enum)]) – The enumeration whose members the value is looked up in.

  • default (TypeVar(_EnumType, bound= Enum) | None) – Optional, the member to return when the option wasn’t given.

Return type:

TypeVar(_EnumType, bound= Enum)

Returns:

The named member of the enumeration.

Raises:
_CreateSingleRowTableHeader(columns, identifier, classes)[source]

Create a table with a single header row.

Parameters:
  • columns (list[tuple[str, int | None]]) – One (title, width) pair per column; a width of None leaves it to the writer.

  • identifier (str) – Identifier of the table.

  • classes (list[str]) – CSS classes to put on the table.

Return type:

tgroup

Returns:

The table’s column group, with the header row already in it.

_CreateDoubleRowTableHeader(columns, identifier, classes)[source]

Create a table whose header spans two rows, so a column can group sub-columns.

A column’s subColumns is None when it spans both header rows, and otherwise holds the (title, width) pairs below it.

Parameters:
Return type:

tgroup

Returns:

The table’s column group, with both header rows already in it.

_CreateRotatedTableHeader(columns, identifier, classes)[source]

Create a table whose header titles are rotated, for many narrow columns.

Parameters:
  • columns (list[tuple[str, list[str] | None]]) – One (title, classes) pair per column; the classes are put on the header cell.

  • identifier (str) – Identifier of the table.

  • classes (list[str]) – CSS classes to put on the table.

Return type:

tgroup

Returns:

The table’s column group, with the header row already in it.

__init__(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)
Return type:

None

_internalError(container, location, message, exception)[source]

Report an exception a directive couldn’t recover from, in the log and on the page.

A directive that fails silently leaves a hole in the documentation that nobody notices. This puts the message where a reader sees it and the traceback where a maintainer does.

Parameters:
  • container (container) – The container the message is put into.

  • location (str) – Name of the logger, which is what the log line is attributed to.

  • message (str) – What went wrong, in one sentence.

  • exception (Exception) – The exception that was caught.

Return type:

list[Node]

Returns:

The container, as the list a directive’s run returns.

_object_hierarchy_parts(sig_node)

Returns a tuple of strings, one entry for each part of the object’s hierarchy (e.g. ('module', 'submodule', 'Class', 'method')). The returned tuple is used to properly nest children within parents in the table of contents, and can also be used within the _toc_entry_name() method.

This method must not be used outwith table of contents generation.

Return type:

tuple[str, ...]

Parameters:

sig_node (desc_signature)

_toc_entry_name(sig_node)

Returns the text of the table of contents entry for the object.

This function is called once, in run(), to set the name for the table of contents entry (a special attribute _toc_name is set on the object node, later used in environment.collectors.toctree.TocTreeCollector.process_doc().build_toc() when the table of contents entries are collected).

To support table of contents entries for their objects, domains must override this method, also respecting the configuration setting toc_object_entries_show_parents. Domains must also override _object_hierarchy_parts(), with one (string) entry for each part of the object’s hierarchy. The result of this method is set on the signature node, and can be accessed as sig_node['_toc_parts'] for use within this method. The resulting tuple is also used to properly nest children within parents in the table of contents.

An example implementations of this method is within the python domain (PyObject._toc_entry_name()). The python domain sets the _toc_parts attribute within the handle_signature() method.

Return type:

str

Parameters:

sig_node (desc_signature)

add_name(node)

Append self.options[‘name’] to node[‘names’] if it exists.

Also normalize the name string and register it as explicit target.

Return type:

None

add_target_and_index(name, sig, signode)

Add cross-reference IDs and entries to self.indexnode, if applicable.

name is whatever handle_signature() returned.

Return type:

None

Parameters:
  • name (ObjDescT)

  • sig (str)

  • signode (desc_signature)

after_content()

Called after parsing content.

Used to reset information about the current directive context on the build environment.

Return type:

None

assert_has_content()

Throw an ERROR-level DirectiveError if the directive doesn’t have contents.

before_content()

Called before parsing content.

Used to set information about the current directive context on the build environment.

Return type:

None

property config: Config

Reference to the Config object.

Added in version 1.8.

directive_error(level, message)

Return a DirectiveError suitable for being thrown as an exception.

Call “raise self.directive_error(level, message)” from within a directive implementation to return one single system message at level level, which automatically gets the directive block and the line number added.

Preferably use the debug, info, warning, error, or severe wrapper methods, e.g. self.error(message) to generate an ERROR-level directive error.

property env: BuildEnvironment

Reference to the BuildEnvironment object.

Added in version 1.8.

get_location()

Get current location info for logging.

Added in version 4.2.

Return type:

str

get_signatures()

Retrieve the signatures to document from the directive arguments.

By default, signatures are given as arguments, one per line.

Return type:

list[str]

get_source_info()

Get source and line number.

Added in version 3.0.

Return type:

tuple[str | None, int | None]

handle_signature(sig, signode)

Parse the signature sig.

The individual nodes are then appended to signode. If ValueError is raised, parsing is aborted and the whole sig is put into a single desc_name node.

The return value should be a value that identifies the object. It is passed to add_target_and_index() unchanged, and otherwise only used to skip duplicates.

Return type:

TypeVar(ObjDescT)

Parameters:
  • sig (str)

  • signode (desc_signature)

parse_content_to_nodes(allow_section_headings=False)

Parse the directive’s content into nodes.

Parameters:

allow_section_headings (bool) – Are titles (sections) allowed in the directive’s content? Note that this option bypasses Docutils’ usual checks on doctree structure, and misuse of this option can lead to an incoherent doctree. In Docutils, section nodes should only be children of Structural nodes, which includes document, section, and sidebar nodes.

Return type:

list[Node]

Added in version 7.4.

Return type:

list[Node]

Parameters:

allow_section_headings (bool)

parse_inline(text, *, lineno=-1)

Parse text as inline elements.

Parameters:
  • text (str) – The text to parse, which should be a single line or paragraph. This cannot contain any structural elements (headings, transitions, directives, etc).

  • lineno (int) – The line number where the interpreted text begins.

Return type:

tuple[list[Node], list[system_message]]

Returns:

A list of nodes (text and inline elements) and a list of system_messages.

Added in version 7.4.

parse_text_to_nodes(text='', /, *, offset=-1, allow_section_headings=False)

Parse text into nodes.

Parameters:
  • text (str) – Text, in string form. StringList is also accepted.

  • allow_section_headings (bool) – Are titles (sections) allowed in text? Note that this option bypasses Docutils’ usual checks on doctree structure, and misuse of this option can lead to an incoherent doctree. In Docutils, section nodes should only be children of Structural nodes, which includes document, section, and sidebar nodes.

  • offset (int) – The offset of the content.

Return type:

list[Node]

Added in version 7.4.

Return type:

list[Node]

Parameters:
  • text (str)

  • offset (int)

  • allow_section_headings (bool)

run()

Main directive entry function, called by docutils upon encountering the directive.

This directive is meant to be quite easily subclassable, so it delegates to several additional methods. What it does:

  • find out if called as a domain-specific directive, set self.domain

  • create a desc node to fit all description inside

  • parse standard options, currently no-index

  • create an index node if needed as self.indexnode

  • parse all given signatures (as returned by self.get_signatures()) using self.handle_signature(), which should either return a name or raise ValueError

  • add index entries using self.add_target_and_index()

  • parse the content and handle doc fields in it

Return type:

list[Node]

set_source_info(node)

Set source and line number to the node.

Added in version 2.1.

Return type:

None

Parameters:

node (Node)

transform_content(content_node)

Can be used to manipulate the content.

Called after creating the content through nested parsing, but before the object-description-transform event is emitted, and before the info-fields are transformed.

Return type:

None

Parameters:

content_node (desc_content)