Skip to content

MkNode

The base class of every node, page and nav: tree handling (parent, children, iter_nodes()), the project context (ctx), the Jinja environment (env) and the async rendering API (await node.to_markdown(), to_html(), get_resources(); sync code uses to_markdown_sync()). to_html(flavor=...) converts with a parser that knows the flavour: Python-Markdown for material, comrak for github / mdbook, markdown-it-py with the MyST plugins (directives mapped to Sphinx-like HTML, an approximation) for myst; the last two need the html extra (pip install mknodes[html]). Its node page (MkNode) shows the examples.

Example
import mknodes as mk

node = mk.MkAdmonition("Careful!", typ="warning")
markdown = await node.to_markdown()
html = await node.to_html()
github_html = await node.to_html(flavor="github")  # needs mknodes[html]
resources = await node.get_resources()  # Markdown extensions, CSS, JS

mknodes.MkNode

Base class for everything which can be expressed as Markup.

This class combines tree node functionality with markdown generation. Starting from the root nav (aka Docs) down to nested Markup blocks, the whole project can be represented by one tree.

MkNode is the base class for all nodes. We dont instanciate it directly. All subclasses carry an MkAnnotations node (except the MkAnnotations node itself) They can also pass an indent as well as a shift_header_levels keyword argument in order to modify the resulting markdown.

ancestors property

ancestors: Iterable[MkNode]

Get iterator to yield all ancestors of self, does not include self.

ctx property

ctx: ProjectContext

The tree context.

Will return the attached context or the closest context from parents. If no context is found, return an "empty" ProjectContext.

depth property

depth: int

Get depth of self, indexing starts from 1.

descendants property

descendants: Iterable[MkNode]

Get iterator to yield all descendants of self, does not include self.

env cached property

env

The node jinja environment.

The environment has additional loaders for the class file path as well as the resolved parent nav file path.

files property

files: dict[str, str | bytes]

Return a dict containing the virtual files attached to this tree element.

This can be overridden by nodes if they want files to be included dynamically. For static files, use add_file.

is_leaf property

is_leaf: bool

Get indicator if self is leaf node.

is_root property

is_root: bool

Get indicator if self is root node.

left_sibling property

left_sibling: MkNode | None

Get sibling left of self.

max_depth property

max_depth: int

Get maximum depth from root to leaf node.

node_path property

node_path: list[MkNode]

Get list of nodes starting from root.

parent property writable

parent: MkNode | None

The parent node of this node.

parent_navs property

parent_navs: list[MkNav]

Return a list of parent MkNavs, ordered from root to leaf.

parent_page property

parent_page: MkPage | None

Return the page which contains this node if existing.

resolved_parts property

resolved_parts: tuple[str, ...]

Return a tuple containing all section names.

right_sibling property

right_sibling: MkNode | None

Get sibling right of self.

root property

root: MkNode

Get root node of tree.

siblings property

siblings: Iterable[MkNode]

Get siblings of self.

__copy__

__copy__(**kwargs: Any) -> Self

Shallow copy self.

__init__

__init__(
    *,
    header: str = "",
    indent: str = "",
    name: str | None = None,
    shift_header_levels: int = 0,
    variables: dict[str, Any] | None = None,
    context: ProjectContext | None = None,
    parent: MkNode | None = None,
    **_kwargs: Any
) -> None

Constructor.

Parameters:

Name Type Description Default
header str

Optional header for contained Markup

''
indent str

Indentation of given Markup (unused ATM)

''
name str | None

An optional unique identifier (allows getting node via MkNode.get_node)

None
shift_header_levels int

Regex-based header level shifting (adds/removes #-chars)

0
variables dict[str, Any] | None

Variables to use for rendering

None
context ProjectContext | None

Context this Nav is connected to.

None
parent MkNode | None

Parent for building the tree

None

add_css_class

add_css_class(class_name: str) -> None

Wrap node markdown with given css class.

Parameters:

Name Type Description Default
class_name str

CSS class to wrap the node with

required

add_file

add_file(filename: str, data: str | bytes) -> None

Add a static file as data to this node.

Parameters:

Name Type Description Default
filename str

Filename of the file to add

required
data str | bytes

Data of the file

required

attach_annotations

attach_annotations(text: str) -> str

Attach annotations block to given markdown.

Can be reimplemented if non-default annotations are needed.

Parameters:

Name Type Description Default
text str

Markdown to annote

required

attach_css_classes

attach_css_classes(text: str) -> str

Attach CSS classes to given markdown in attr-list style.

Can be reimplemented if non-default behavior is needed. Default behavior is appending the css class snippet with a space as separator.

Parameters:

Name Type Description Default
text str

Markdown to annote

required

get_children

get_children() -> list[MkNode]

Return the list of children nodes.

get_content async

get_content() -> NodeContent

Return markdown and resources for this node in a single pass.

Override this method in subclasses to compute both markdown and resources together when they share expensive computation.

Default implementation calls legacy methods to_md_unprocessed() and _build_node_resources() for backward compatibility.

get_node classmethod

get_node(name: str) -> MkNode

Get a node from name registry.

get_node_resources async

get_node_resources() -> Resources

Return the resources specific for this node.

Default implementation calls _build_node_resources(). Override get_content() if you need to compute markdown and resources together.

get_nodefile classmethod

get_nodefile() -> NodeFile | None

Return the NodeFile if existing.

get_processors

get_processors() -> list[TextProcessor]

Return list of processors used to created markdown.

get_resources async

get_resources() -> Resources

Return the "final" resources object.

is_descendant_of

is_descendant_of(kls: type | UnionType) -> bool

Returns True if any ancestor is of given type.

Parameters:

Name Type Description Default
kls type | UnionType

The class (union) the check the ancestors for

required

iter_nodes

iter_nodes(indent: int = 0, max_depth: int | None = None) -> Iterator[tuple[int, MkNode]]

Iterate over all nodes, including self and children.

Yields current-depth-node tuples.

Parameters:

Name Type Description Default
indent int

The start "level". The first element of the returned tuple will be relative to this

0
max_depth int | None

The max depth to iterate

None

row

row() -> int

Return the position of this node inside the parent's children list.

to_child_node

to_child_node(other: str | list[Any] | MkNode | None)

Convert given nodes / strings to child nodes.

Either converts text to an MkNode sets parent of node to self.

Parameters:

Name Type Description Default
other str | list[Any] | MkNode | None

The node / string to convert to a child node.

required

to_html async

to_html(flavor: str | Renderer | None = None) -> str

Convert node to HTML using the resources from node + children.

The Markdown is rendered in given flavour (default: the active one) and converted with a parser knowing that flavour (Renderer.to_html, see rendering.html).

Parameters:

Name Type Description Default
flavor str | Renderer | None

Markdown flavour (renderer name like "github" or a Renderer).

None

to_markdown async

to_markdown(flavor: str | Renderer | None = None) -> str

Outputs markdown for self and all children (a coroutine: await it).

Sync code (scripts, no running event loop) can use to_markdown_sync().

Parameters:

Name Type Description Default
flavor str | Renderer | None

Markdown flavour (renderer name like "github" or a Renderer). Defaults to the active renderer (Material for MkDocs).

None

to_markdown_sync

to_markdown_sync(flavor: str | Renderer | None = None) -> str

Blocking version of to_markdown() for sync code.

Also works while an event loop is running (it then renders in a worker thread), async code should await node.to_markdown() instead.

Parameters:

Name Type Description Default
flavor str | Renderer | None

Markdown flavour (renderer name like "github" or a Renderer). Defaults to the active renderer (Material for MkDocs).

None

to_md_unprocessed async

to_md_unprocessed() -> str

Return raw markdown for this node. Override in subclasses for custom markdown.

with_context classmethod

with_context(
    *args: Any, repo_url: str | None = None, base_url: str = "", **kwargs: Any
) -> Self

Same as the Ctor, but auto-adds a context for the repo url (or the cwd).

Page info
Code for this page
mknodes.manual.api_section._add_page.<locals>._
@nav.route.page(title, hide="toc")
def _(page: mk.MkPage) -> None:
    page += INTROS[title]
    page += mk.MkCode(EXAMPLES[title].rstrip(), language="py", title="Example")
    for identifier in identifiers:
        page += mk.MkDocStrings(identifier, **DOCSTRING_OPTIONS)
Resources
Resources(css=[],
          markdown_extensions={'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/api_section.py
  source_function: _add_page.<locals>._
  source_line_no: 168
hide:
- toc
title: MkNode