sphinx_toolbox.utils

General utility functions.

Functions:

add_nbsp_substitution(config)

Adds the |nbsp| substitution directive to the reStructuredText prolog.

allow_subclass_add(app, *documenters)

Add the given autodocumenters, but only if a subclass of it is not already registered.

baseclass_is_private(obj)

Returns True if the first and only base class starts with a double underscore.

code_repr(obj)

Returns the repr of the given object as reStructuredText inline code.

escape_trailing__(string)

Returns the given string with trailing underscores escaped to prevent Sphinx treating them as references.

filter_members_warning(member, exception)

Log a warning when filtering members.

flag(argument)

Check for a valid flag option (no argument) and return True.

get_first_matching(condition, iterable[, …])

Returns the first value in iterable that meets condition, or default if none match.

is_namedtuple(obj)

Returns whether the given object is a collections.namedtuple() class.

make_github_url(username, repository)

Construct a URL to a GitHub repository from a username and repository name.

parse_parameters(lines[, tab_size])

Parse parameters from the docstring of a class/function.

unknown_module_warning(documenter)

Log a warning that the module to import the object from is unknown.

add_fallback_css_class(objtypes_css_fallbacks)

Registers a transform which will edit the CSS classes of documented objects based on their objtype.

Data:

GITHUB_COM

Instance of apeye.requests_url.RequestsURL that points to the GitHub website.

OptionSpec

Type hint for the option_spec variable of Docutils directives.

SetupFunc

Type annotation for Sphinx extensions’ setup functions.

typed_flag_regex

Regex to match :type <name>: <type> flags.

typed_param_regex

Regex to match :param <type> <name>: <docstring> flags.

untyped_param_regex

Regex to match :param <name>: <docstring> flags.

Exceptions:

NoMatchError

Raised when no matching values were found in get_first_matching().

Classes:

Param

TypedDict to represent a parameter parsed from a class or function’s docstring.

Purger(attr_name)

Class to purge redundant nodes.

SphinxExtMetadata

typing.TypedDict representing the metadata dictionary returned by Sphinx extensions’ setup functions.

add_nbsp_substitution(config)[source]

Adds the |nbsp| substitution directive to the reStructuredText prolog.

New in version 2.1.0.

Parameters

config (Config)

allow_subclass_add(app, *documenters)[source]

Add the given autodocumenters, but only if a subclass of it is not already registered.

This allows other libraries to extend the autodocumenters.

New in version 0.8.0.

Parameters
  • app (Sphinx) – The Sphinx application.

  • documenters

baseclass_is_private(obj)[source]

Returns True if the first and only base class starts with a double underscore.

Parameters

obj (Type)

Return type

bool

code_repr(obj)[source]

Returns the repr of the given object as reStructuredText inline code.

New in version 0.9.0.

Parameters

obj (Any)

Return type

str

escape_trailing__(string)[source]

Returns the given string with trailing underscores escaped to prevent Sphinx treating them as references.

New in version 0.8.0.

Parameters

string (str)

Return type

str

filter_members_warning(member, exception)[source]

Log a warning when filtering members.

New in version 0.2.0.

Parameters
flag(argument)[source]

Check for a valid flag option (no argument) and return True.

Used in the option_spec of directives.

See also

docutils.parsers.rst.directives.flag, which returns None instead of True.

Raises

ValueError if an argument is given.

Return type

bool

get_first_matching(condition, iterable, default=no_default)[source]

Returns the first value in iterable that meets condition, or default if none match.

New in version 0.7.0.

Parameters
  • condition (Callable[[Any], bool]) – The condition to evaluate.

  • iterable (Iterable[~_T])

  • default (~_T) – The default value to return if no values in iterable match. Default no_default.

Return type

~_T

GITHUB_COM = RequestsURL('https://github.com')

Type:    RequestsURL

Instance of apeye.requests_url.RequestsURL that points to the GitHub website.

is_namedtuple(obj)[source]

Returns whether the given object is a collections.namedtuple() class.

New in version 0.8.0.

Parameters

obj (Any)

Return type

bool

make_github_url(username, repository)[source]

Construct a URL to a GitHub repository from a username and repository name.

Parameters
  • username (str) – The username of the GitHub account that owns the repository.

  • repository (str) – The name of the repository.

Return type

RequestsURL

exception NoMatchError[source]

Bases: ValueError

Raised when no matching values were found in get_first_matching().

New in version 0.7.0.

OptionSpec

Type hint for the option_spec variable of Docutils directives.

Alias of Mapping[str, Callable[[str], Any]]

typeddict Param[source]

Bases: dict

TypedDict to represent a parameter parsed from a class or function’s docstring.

New in version 0.8.0.

Required Keys
  • doc (List[str]) – The docstring of the parameter.

  • type (str) – The type of the parameter.

parse_parameters(lines, tab_size=8)[source]

Parse parameters from the docstring of a class/function.

New in version 0.8.0.

Parameters
  • lines (List[str]) – The lines of the docstring

  • tab_size (int) – Default 8.

Return type

Tuple[Dict[str, Param], List[str], List[str]]

Returns

A mapping of parameter names to their docstrings and types, a list of docstring lines that appeared before the parameters, and the list of docstring lines that appear after the parameters.

class Purger(attr_name)[source]

Bases: object

Class to purge redundant nodes.

Parameters

attr_name (str) – The name of the build environment’s attribute that stores the list of nodes, e.g. all_installation_nodes.

Methods:

purge_nodes(app, env, docname)

Remove all redundant nodes.

get_outdated_docnames(app, env, added, …)

Returns a list of all docnames containing one or more nodes this Purger is aware of.

add_node(env, node, targetnode, lineno)

Add a node.

purge_nodes(app, env, docname)[source]

Remove all redundant nodes.

This function can be configured for the env-purge-doc event:

my_node_purger = Purger("all_my_node_nodes")

def setup(app: Sphinx):
    app.connect("env-purge-doc", my_node_purger.purge_nodes)
Parameters
  • app (Sphinx) – The Sphinx application.

  • env (BuildEnvironment) – The Sphinx build environment.

  • docname (str) – The name of the document to remove nodes for.

get_outdated_docnames(app, env, added, changed, removed)[source]

Returns a list of all docnames containing one or more nodes this Purger is aware of.

This function can be configured for the env-get-outdated event:

my_node_purger = Purger("all_my_node_nodes")

def setup(app: Sphinx):
    app.connect("env-get-outdated", my_node_purger.get_outdated_docnames)

New in version 2.7.0.

Parameters
  • app (Sphinx) – The Sphinx application.

  • env (BuildEnvironment) – The Sphinx build environment.

  • added (Set[str]) – A set of newly added documents.

  • changed (Set[str]) – A set of document names whose content has changed.

  • removed (Set[str]) – A set of document names which have been removed.

Return type

List[str]

add_node(env, node, targetnode, lineno)[source]

Add a node.

Parameters
  • env (BuildEnvironment) – The Sphinx build environment.

  • node (Node)

  • targetnode (Node)

  • lineno (int)

SetupFunc

Type annotation for Sphinx extensions’ setup functions.

New in version 1.9.0.

Alias of Callable[[Sphinx], Optional[SphinxExtMetadata]]

typeddict SphinxExtMetadata[source]

Bases: dict

typing.TypedDict representing the metadata dictionary returned by Sphinx extensions’ setup functions.

This is treated by Sphinx as metadata of the extension.

Optional Keys
  • version (str) – A string that identifies the extension version. It is used for extension version requirement checking and informational purposes. If not given, 'unknown version' is substituted.

  • env_version (int) – An integer that identifies the version of env data structure if the extension stores any data to environment. It is used to detect the data structure has been changed from last build. Extensions have to increment the version when data structure has changed. If not given, Sphinx considers the extension does not stores any data to environment.

  • parallel_read_safe (bool) – A boolean that specifies if parallel reading of source files can be used when the extension is loaded. It defaults to False, i.e. you have to explicitly specify your extension to be parallel-read-safe after checking that it is.

  • parallel_write_safe (bool) – A boolean that specifies if parallel writing of output files can be used when the extension is loaded. Since extensions usually don’t negatively influence the process, this defaults to True.

typed_flag_regex

Type:    Pattern[str]

Regex to match :type <name>: <type> flags.

New in version 0.8.0.

Pattern

^:(paramtype|type)\s*([A-Za-z_]\w*\s*):\s*(.*)

Flags

re.ASCII

typed_param_regex

Type:    Pattern[str]

Regex to match :param <type> <name>: <docstring> flags.

New in version 0.8.0.

Pattern

^:(param|parameter|arg|argument)\s*([A-Za-z_]\w*\s+)([A-Za-z_]\w*\s*):\s*(.*)

Flags

re.ASCII

unknown_module_warning(documenter)[source]

Log a warning that the module to import the object from is unknown.

New in version 0.2.0.

Parameters

documenter (Documenter)

untyped_param_regex

Type:    Pattern[str]

Regex to match :param <name>: <docstring> flags.

New in version 0.8.0.

Pattern

^:(param|parameter|arg|argument)\s*([A-Za-z_]\w*\s*):\s*(.*)

Flags

re.ASCII

add_fallback_css_class(objtypes_css_fallbacks)[source]

Registers a transform which will edit the CSS classes of documented objects based on their objtype.

Parameters

objtypes_css_fallbacks (Dict[str, str]) – A mapping of Sphinx objtypes to the CSS class which should be added to them. The class is usually the objtype attribute from the documenter’s parent class.

New in version 2.16.0.

Used as follows:

app.connect("object-description-transform", add_fallback_css_class({"typeddict": "class"}))

This will apply the transformation to documented objects with the typeddict CSS class by adding the class CSS class.

Parameters

objtypes_css_fallbacks

Return type

Callable[[Sphinx, str, str, desc_content], None]