Skip to content

Module API - Nodes

Alt Text

Prefer from clak import Parser for app code. Node internals:

clak.core.nodes

Node tree and Meta configuration lookup (base of ParserNode).

A setting <name> is declared with meta__config__<name> and read, in order, from self._<name>, self.Meta.<name> then self.meta__<name>.

Node

A named node in a parent/children tree with Meta settings lookup

Source code in clak/core/nodes.py
class Node:
    "A named node in a parent/children tree with Meta settings lookup"

    name: str | None = None
    parent: "Node | None" = None

    class Meta:
        """Class-level configuration overrides (empty container)."""

    def __init__(self, name=None, parent=None):
        self.name = self.__class__.__name__ if name is None else name
        if not isinstance(self.name, str):
            raise TypeError(f"Node name must be a str, got {type(self.name).__name__}")

        self.parent = parent
        if not isinstance(self.parent, (Node, type(None))):
            raise TypeError(
                f"Node parent must be a Node or None, got {type(self.parent).__name__}"
            )

    def get_hierarchy(self):
        "Return the nodes from the root down to self"
        hierarchy = []
        current = self
        while current is not None:
            hierarchy.append(current)
            current = current.parent
        hierarchy.reverse()
        return hierarchy

    def get_fname(self, attr="name"):
        "Return the dotted full name of the node (from ``attr`` of each node)"
        return ".".join(getattr(x, attr, None) or "" for x in self.get_hierarchy())

    def query_cfg_parents(
        self, name: str, default: Any = _REQUIRED, include_self: bool = True
    ) -> Any:
        """Query a setting from this node (or its parent) up to the root.

        The setting must be declared (``meta__config__<name>``) on at least
        one node of the lookup chain; values are then read from every node,
        closest first, so a plain subcommand's ``Meta`` overrides a setting
        declared by a mixin on an ancestor.

        Raises:
            MissingMetaError: The setting is not declared in the lookup chain
            ConfigurationError: No value found and no default provided
        """
        declare_attr = f"meta__config__{name}"
        node = self if include_self else self.parent
        if node is None:
            if default is not _REQUIRED:
                return default
            raise ConfigurationError(self._not_declared_msg(name))

        # Single pass, closest node first: remember the first value found and
        # whether any node of the chain declares the setting.
        declared = False
        found = NOT_SET
        while node is not None:
            if not declared and getattr(node, declare_attr, None) is not None:
                declared = True
            if found is NOT_SET:
                found = node.query_cfg_inst(name, default=NOT_SET)
            if declared and found is not NOT_SET:
                return found
            node = node.parent

        if not declared:
            raise MissingMetaError(
                f"Missing '{declare_attr}', "
                f"this option has not been declared in any parents of {self!r}"
            )
        if default is _REQUIRED:
            raise ConfigurationError(self._not_declared_msg(name))
        return default

    def _not_declared_msg(self, name: str) -> str:
        return f"Setting '{name}' has not been declared in hierarchy of '{self!r}'"

    def query_cfg_inst(self, name, default=_REQUIRED):
        """Query a setting on this node only (dict/list values are copied).

        Lookup: ``self._<name>``, ``self.Meta.<name>``, ``self.meta__<name>``,
        then *default*. Raises ``IndexError`` when nothing matches.
        """
        out = getattr(self, f"_{name}", NOT_SET)
        if out is NOT_SET:
            out = getattr(getattr(self, "Meta", None), name, NOT_SET)
        if out is NOT_SET:
            out = getattr(self, f"meta__{name}", NOT_SET)
        if out is NOT_SET:
            if default is _REQUIRED:
                raise IndexError(
                    f"Setting '{name}' has not been declared before being used"
                    f" in '{self!r}'"
                )
            return default

        if isinstance(out, (dict, list)):
            out = copy.copy(out)
        return out

Meta

Class-level configuration overrides (empty container).

Source code in clak/core/nodes.py
class Meta:
    """Class-level configuration overrides (empty container)."""

get_fname(attr='name')

Return the dotted full name of the node (from attr of each node)

Source code in clak/core/nodes.py
def get_fname(self, attr="name"):
    "Return the dotted full name of the node (from ``attr`` of each node)"
    return ".".join(getattr(x, attr, None) or "" for x in self.get_hierarchy())

get_hierarchy()

Return the nodes from the root down to self

Source code in clak/core/nodes.py
def get_hierarchy(self):
    "Return the nodes from the root down to self"
    hierarchy = []
    current = self
    while current is not None:
        hierarchy.append(current)
        current = current.parent
    hierarchy.reverse()
    return hierarchy

query_cfg_inst(name, default=_REQUIRED)

Query a setting on this node only (dict/list values are copied).

Lookup: self._<name>, self.Meta.<name>, self.meta__<name>, then default. Raises IndexError when nothing matches.

Source code in clak/core/nodes.py
def query_cfg_inst(self, name, default=_REQUIRED):
    """Query a setting on this node only (dict/list values are copied).

    Lookup: ``self._<name>``, ``self.Meta.<name>``, ``self.meta__<name>``,
    then *default*. Raises ``IndexError`` when nothing matches.
    """
    out = getattr(self, f"_{name}", NOT_SET)
    if out is NOT_SET:
        out = getattr(getattr(self, "Meta", None), name, NOT_SET)
    if out is NOT_SET:
        out = getattr(self, f"meta__{name}", NOT_SET)
    if out is NOT_SET:
        if default is _REQUIRED:
            raise IndexError(
                f"Setting '{name}' has not been declared before being used"
                f" in '{self!r}'"
            )
        return default

    if isinstance(out, (dict, list)):
        out = copy.copy(out)
    return out

query_cfg_parents(name, default=_REQUIRED, include_self=True)

Query a setting from this node (or its parent) up to the root.

The setting must be declared (meta__config__<name>) on at least one node of the lookup chain; values are then read from every node, closest first, so a plain subcommand's Meta overrides a setting declared by a mixin on an ancestor.

Raises:

Type Description
MissingMetaError

The setting is not declared in the lookup chain

ConfigurationError

No value found and no default provided

Source code in clak/core/nodes.py
def query_cfg_parents(
    self, name: str, default: Any = _REQUIRED, include_self: bool = True
) -> Any:
    """Query a setting from this node (or its parent) up to the root.

    The setting must be declared (``meta__config__<name>``) on at least
    one node of the lookup chain; values are then read from every node,
    closest first, so a plain subcommand's ``Meta`` overrides a setting
    declared by a mixin on an ancestor.

    Raises:
        MissingMetaError: The setting is not declared in the lookup chain
        ConfigurationError: No value found and no default provided
    """
    declare_attr = f"meta__config__{name}"
    node = self if include_self else self.parent
    if node is None:
        if default is not _REQUIRED:
            return default
        raise ConfigurationError(self._not_declared_msg(name))

    # Single pass, closest node first: remember the first value found and
    # whether any node of the chain declares the setting.
    declared = False
    found = NOT_SET
    while node is not None:
        if not declared and getattr(node, declare_attr, None) is not None:
            declared = True
        if found is NOT_SET:
            found = node.query_cfg_inst(name, default=NOT_SET)
        if declared and found is not NOT_SET:
            return found
        node = node.parent

    if not declared:
        raise MissingMetaError(
            f"Missing '{declare_attr}', "
            f"this option has not been declared in any parents of {self!r}"
        )
    if default is _REQUIRED:
        raise ConfigurationError(self._not_declared_msg(name))
    return default