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:renderparses 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-mystalways parses the captured output as MyST, regardless of host. Lets.rstdocuments embed MyST-generated content.python:render-rstalways parses the captured output as reST, regardless of host. Lets.mddocuments 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 byupdate_mirror_blocks(): edit the Python block above the marker, never the mirrored region itself. Same<!-- name --> / <!-- name-end -->grammar as the<!-- matrix … -->regions ofclick_extra.sphinx.matrix.
- click_extra.sphinx.python.MIRROR_MARKER_END = '<!-- mirror-end -->'¶
Closing marker of a
:mirror:region. SeeMIRROR_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 byupdate_mirror_blocks(); edit the comment, never the body.
- class click_extra.sphinx.python.PythonRunner(capture=None)[source]¶
Bases:
objectStateful runner for
python:*directives.Holds a per-document namespace so consecutive directive blocks share imports and variables. One instance is attached to
state.documenton first use and dropped atdoctree-readtime bycleanup_python_runner().- execute_source(directive)[source]¶
Execute the directive’s content with no output capture.
Used by
PythonSourceDirectivewhen the example is run only for its side effects (typically to seed imports for a follow-uppython:runblock).- Return type:
- class click_extra.sphinx.python.PythonDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Bases:
ClickDirectiveBase 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:
PythonDirectiveRender a Python source block and execute it silently.
Counterpart to
SourceDirectivefor non-Click code: show the source for teaching, run it as a side effect to seed the runner namespace for subsequentpython:runorpython:renderblocks 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
ClickRunnerfor theclick:*directives.
- screenshots_source: bool = True¶
Whether a
:screenshot:on this directive pictures the block’s own code.Falsefor a directive that runs something: what is worth committing there is the output, and the code producing it is on the page already.Truefor one that only declares code, which has no output to picture and whose subject is the code itself. Seescreenshot_lines().
- class click_extra.sphinx.python.PythonRunDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Bases:
PythonDirectiveExecute 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 aspythonwhatever the result language, and a:screenshot:pictures the captured output, as it does onclick: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
ClickRunnerfor theclick:*directives.
- source_language: str | None = 'python'¶
Language the source block is highlighted in, when it is not
language.Nonefor a directive showing code of the language it names: the source block of aclick:sourcefollows 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,pythonfor 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:
PythonDirectiveCommon scaffolding for the
python:renderdirective family.Subclasses set
forced_parserto eitherNone(use the host document’s parser viastate.nested_parse) or aParserfactory 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
ClickRunnerfor theclick:*directives.
- forced_parser: ClassVar[type[Parser] | None] = None¶
Parser class to instantiate for the captured output.
Nonemeans defer to the host document’s parser viastate.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 thesource-readpass, 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:
PythonRenderBaseDirectiveExecute a Python block and parse its
stdoutwith the host parser.The captured output is fed to whatever parser owns the surrounding source file: MyST inside
.mddocuments, reST inside.rstdocuments. 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
PythonRenderMystDirectiveandPythonRenderRstDirective.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, betweenMIRROR_MARKER_START/MIRROR_MARKER_ENDmarkers, so the output is reviewable in place and renders on GitHub. The committed region is refreshed byupdate_mirror_blocks(); builds render fresh output viarewrite_python_mirror_regions().
- class click_extra.sphinx.python.PythonRenderMystDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Bases:
PythonRenderBaseDirectiveExecute a Python block and parse its
stdoutas MyST, regardless of host.Lets a
.rstdocument embed MyST-generated content: the captured output goes through MyST parsing even when the surrounding file is reST. Requiresmyst-parserto 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.pyregenerator 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.
- class click_extra.sphinx.python.PythonRenderRstDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]¶
Bases:
PythonRenderBaseDirectiveExecute a Python block and parse its
stdoutas reST, regardless of host.Lets a
.mdMyST 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
textwith both kinds of mirror region refreshed.The fence form first (
_rewrite_mirror_regions), then the comment form (_rewrite_mirror_src_regions), each only whentextcan hold one: a walk costs a pass over every line of the document.- Return type:
- 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, andcheck-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.
- click_extra.sphinx.python.rewrite_python_mirror_regions(app, docname, source)[source]¶
source-readhandler 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-memorysourcebefore 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 byupdate_mirror_blocks(), behind theclick-extra refresh-directivescommand.Danger
Like the
python:*directives, this executes arbitrary Python at build time with the full privileges of the Sphinx process. It is registered only whenclick_extra_enable_exec_directivesis set.- Return type:
- class click_extra.sphinx.python.PythonDomain(env)[source]¶
Bases:
StatelessDomainSphinx domain registering the
python:*directives.Provides:
python:sourceto show and silently execute Python source.python:runto execute Python and render the captured stdout in a code block.python:renderto execute Python and parse the captured stdout with the host document’s parser.python:render-mystto force MyST parsing of the captured stdout.python:render-rstto force reST parsing of the captured stdout.
The domain name is
python, distinct from Sphinx’s built-inpydomain (which providespy:function/py:class/py:modfor documenting Python API objects). Both coexist without collision.- 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
PythonRunnerfrom the doctree once the document is read.- Return type: