click_extra.sphinx.python module¶

Generic Python execution directives for Sphinx documentation.

Sibling to click_extra.sphinx.click. The Click directives execute a Click CLI and render its terminal output; these execute arbitrary Python and render either captured stdout (python:run) or live document content parsed from the captured output (python:render, python:render-myst, python:render-rst).

The render trio lets a documentation page embed dynamically generated tables, references, or whole sections without a separate docs_update.py regenerator script: the content stays in sync with its source by construction.

Each render variant has a clear parser contract:

  • python:render parses the captured output with whatever parser owns the host document. Use it when the generated markup matches the host file format (MyST inside .md, reST inside .rst).

  • python:render-myst always parses the captured output as MyST, regardless of host. Lets .rst documents embed MyST-generated content.

  • python:render-rst always parses the captured output as reST, regardless of host. Lets .md documents embed reST-generated content.

On top of live rendering, python:render accepts a :mirror: flag. A mirror block keeps a copy of its generated Markdown in the source .md, between MIRROR_MARKER_START / MIRROR_MARKER_END markers directly below the fence, so the output is reviewable in place and renders on GitHub. The committed region is refreshed by update_mirror_blocks() (behind the click-extra refresh-directives command, alongside the {matrix} blocks of click_extra.sphinx.matrix), while Sphinx builds always render the fresh output by regenerating the region in memory at source-read time: the marker region of a docs_update.py script, with the generator inlined into the page.

click_extra.sphinx.python.MIRROR_MARKER_START = '<!-- mirror -->'¶

Opening marker of a python:render :mirror: region.

Written on its own line, directly below the fence, and paired with MIRROR_MARKER_END. Everything between the two markers is regenerated by update_mirror_blocks(): edit the Python block above the marker, never the mirrored region itself. Same <!-- name --> / <!-- name-end --> grammar as the <!-- matrix … --> regions of click_extra.sphinx.matrix.

click_extra.sphinx.python.MIRROR_MARKER_END = '<!-- mirror-end -->'¶

Closing marker of a :mirror: region. See MIRROR_MARKER_START.

click_extra.sphinx.python.MIRROR_SRC_MARKER_END = '<!-- mirror-src-end -->'¶

Closing marker of a <!-- mirror-src … --> region.

The comment form of :mirror:: the generator Python lives inside an <!-- mirror-src … --> HTML comment instead of a visible {python:render} fence, so the generated body renders on GitHub or PyPI (a README diagram, a compatibility table) while the generator stays invisible. Everything between the opening comment’s closing --> and this marker is regenerated by update_mirror_blocks(); edit the comment, never the body.

class click_extra.sphinx.python.PythonRunner(capture=None)[source]¶

Bases: object

Stateful runner for python:* directives.

Holds a per-document namespace so consecutive directive blocks share imports and variables. One instance is attached to state.document on first use and dropped at doctree-read time by cleanup_python_runner().

namespace: dict[str, object]¶
execute_source(directive)[source]¶

Execute the directive’s content with no output capture.

Used by PythonSourceDirective when the example is run only for its side effects (typically to seed imports for a follow-up python:run block).

Return type:

None

run_python(directive)[source]¶

Execute the directive’s content and capture stdout.

Returns the captured output as a list of lines, suitable for either a code-block render (python:run) or a live nested-parse pass (the python:render directives).

Return type:

list[str]

class click_extra.sphinx.python.PythonDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: ClickDirective

Base class for python:* directives.

Reuses the option spec and rendering scaffolding of ClickDirective, but rebinds the per-document runner so the Click and Python namespaces don’t collide within the same document.

runner_attr: ClassVar[str] = 'python_runner'¶

Name of the attribute holding the runner on the doctree.

Subclasses (like PythonDirective) override this so the Click and Python runners don’t collide on the same document.

runner_factory¶

alias of PythonRunner

class click_extra.sphinx.python.PythonSourceDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonDirective

Render a Python source block and execute it silently.

Counterpart to SourceDirective for non-Click code: show the source for teaching, run it as a side effect to seed the runner namespace for subsequent python:run or python:render blocks in the same document.

default_language: str = 'python'¶

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = True¶

Whether to render the source code of the example in the code block.

show_results_by_default: bool = False¶

Whether to render the results of the example in the code block.

runner_method: str = 'execute_source'¶

The name of the method to call on the per-document runner.

A ClickRunner for the click:* directives.

screenshots_source: bool = True¶

Whether a :screenshot: on this directive pictures the block’s own code.

False for a directive that runs something: what is worth committing there is the output, and the code producing it is on the page already. True for one that only declares code, which has no output to picture and whose subject is the code itself. See screenshot_lines().

class click_extra.sphinx.python.PythonRunDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonDirective

Execute a Python block and render its captured stdout.

Default language for the result code block is text (plain, no highlighting). Override with the :language: option when the output is structured (json, html, yaml, etc.). The source, when shown, is rendered as python whatever the result language, and a :screenshot: pictures the captured output, as it does on click:run.

default_language: str = 'text'¶

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = False¶

Whether to render the source code of the example in the code block.

show_results_by_default: bool = True¶

Whether to render the results of the example in the code block.

runner_method: str = 'run_python'¶

The name of the method to call on the per-document runner.

A ClickRunner for the click:* directives.

source_language: str | None = 'python'¶

Language the source block is highlighted in, when it is not language.

None for a directive showing code of the language it names: the source block of a click:source follows its :language: option. A directive that runs a block names the language of its results instead, so it states the language of the code producing them here, python for every runner of this package.

class click_extra.sphinx.python.PythonRenderBaseDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonDirective

Common scaffolding for the python:render directive family.

Subclasses set forced_parser to either None (use the host document’s parser via state.nested_parse) or a Parser factory that produces the parser to apply to the captured output.

default_language: str = 'markdown'¶

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = False¶

Whether to render the source code of the example in the code block.

show_results_by_default: bool = True¶

Whether to render the results of the example in the code block.

runner_method: str = 'run_python'¶

The name of the method to call on the per-document runner.

A ClickRunner for the click:* directives.

forced_parser: ClassVar[type[Parser] | None] = None¶

Parser class to instantiate for the captured output.

None means defer to the host document’s parser via state.nested_parse (preserving full Sphinx context). A concrete class forces that parser regardless of host file format.

run()[source]¶

Render the captured stdout as live document content.

A :mirror: block is not run here. rewrite_python_mirror_regions() writes its output as a raw Markdown region below the fence during the source-read pass, and the host parser renders that region: the directive shows at most its Python source, so the content is not rendered twice.

Return type:

list[Node]

class click_extra.sphinx.python.PythonRenderDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonRenderBaseDirective

Execute a Python block and parse its stdout with the host parser.

The captured output is fed to whatever parser owns the surrounding source file: MyST inside .md documents, reST inside .rst documents. Use this when the generated markup matches the host file format. Cross-references and Sphinx-aware roles resolve naturally because the host state machine is reused.

For a host-independent contract, see PythonRenderMystDirective and PythonRenderRstDirective.

Accepts an extra :mirror: flag on top of the shared option spec. When set, the block keeps a copy of its generated Markdown in the source file, between MIRROR_MARKER_START / MIRROR_MARKER_END markers, so the output is reviewable in place and renders on GitHub. The committed region is refreshed by update_mirror_blocks(); builds render fresh output via rewrite_python_mirror_regions().

forced_parser: ClassVar[type[Parser] | None] = None¶

Parser class to instantiate for the captured output.

None means defer to the host document’s parser via state.nested_parse (preserving full Sphinx context). A concrete class forces that parser regardless of host file format.

class click_extra.sphinx.python.PythonRenderMystDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonRenderBaseDirective

Execute a Python block and parse its stdout as MyST, regardless of host.

Lets a .rst document embed MyST-generated content: the captured output goes through MyST parsing even when the surrounding file is reST. Requires myst-parser to be importable; the import is deferred to directive run time so consumers that never use this directive don’t pay the dependency cost.

Replaces the docs_update.py regenerator pattern (write generated content between <!-- start --> / <!-- end --> markers) with inline build-time execution. The content is always current and there is no separate regeneration step.

property forced_parser: type[Parser]¶

The MyST docutils parser, imported on first use.

class click_extra.sphinx.python.PythonRenderRstDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶

Bases: PythonRenderBaseDirective

Execute a Python block and parse its stdout as reST, regardless of host.

Lets a .md MyST document embed reST-generated content: the captured output goes through the docutils reST parser even when the surrounding file is MyST. No additional dependency: the reST parser ships with docutils.

forced_parser¶

alias of Parser

click_extra.sphinx.python.rewrite_mirrors(text, location)[source]¶

Return text with both kinds of mirror region refreshed.

The fence form first (_rewrite_mirror_regions), then the comment form (_rewrite_mirror_src_regions), each only when text can hold one: a walk costs a pass over every line of the document.

Return type:

str

click_extra.sphinx.python.update_mirror_blocks(paths, *, check=False)[source]¶

Refresh every python:render :mirror: region in the given sources.

See click_extra.markdown.blocks.update_blocks() for the walk, write, and check-mode contract.

Danger

Refreshing executes each mirror block’s Python with the privileges of the current process, exactly as a documentation build would. Only run it on trusted sources.

Return type:

list[Path]

Returns:

the files whose mirror regions were (or, under check, would be) updated.

click_extra.sphinx.python.rewrite_python_mirror_regions(app, docname, source)[source]¶

source-read handler refreshing :mirror: regions in memory.

Refreshes both kinds of region, below a visible {python:render} :mirror: fence and below an invisible <!-- mirror-src --> comment, in the in-memory source before the document is parsed, so every build renders the fresh output even when the committed region is stale. Nothing is written to disk: the committed region is refreshed offline by update_mirror_blocks(), behind the click-extra refresh-directives command.

Danger

Like the python:* directives, this executes arbitrary Python at build time with the full privileges of the Sphinx process. It is registered only when click_extra_enable_exec_directives is set.

Return type:

None

class click_extra.sphinx.python.PythonDomain(env)[source]¶

Bases: StatelessDomain

Sphinx domain registering the python:* directives.

Provides:

  • python:source to show and silently execute Python source.

  • python:run to execute Python and render the captured stdout in a code block.

  • python:render to execute Python and parse the captured stdout with the host document’s parser.

  • python:render-myst to force MyST parsing of the captured stdout.

  • python:render-rst to force reST parsing of the captured stdout.

The domain name is python, distinct from Sphinx’s built-in py domain (which provides py:function / py:class / py:mod for documenting Python API objects). Both coexist without collision.

name: ClassVar[str] = 'python'¶

domain name: should be short, but unique

label: ClassVar[str] = 'Python (build-time execution)'¶

domain label: longer, more descriptive (used in messages)

directives: ClassVar[dict] = {'render': <class 'click_extra.sphinx.python.PythonRenderDirective'>, 'render-myst': <class 'click_extra.sphinx.python.PythonRenderMystDirective'>, 'render-rst': <class 'click_extra.sphinx.python.PythonRenderRstDirective'>, 'run': <class 'click_extra.sphinx.python.PythonRunDirective'>, 'source': <class 'click_extra.sphinx.python.PythonSourceDirective'>}¶

directive name -> directive class

click_extra.sphinx.python.cleanup_python_runner(app, doctree)¶

Drop the PythonRunner from the doctree once the document is read.

Return type:

None