stree: Reorder StringTree class members

Reorder the StringTree class members to follow the project coding
style:

1. Nested public/helper types (Error, Match) at the top.
2. Instance attribute annotations so mypy can track them before
   __adopt_children runs in __init__.
3. Private methods (__adopt_children, __set, __dump, __find) grouped
   together, with _dict_to_tree moved from module scope into the
   class as a @staticmethod.
4. Dunder methods (__repr__ through __len__) between private and public.
5. Public API preceded by # -- Public API comment, with __init__
   moved from the top into this section.
6. _dict_to_tree recursive call updated to StringTree._dict_to_tree()
   to avoid the bare-name lookup that mypy rejects on a @staticmethod.

Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.80.2
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-07-13 13:48:44 +02:00 • committed by janware DevOps
commit df5202f4dc
Signed by: DevOps
SSH key fingerprint: SHA256:cZiw7ExG5q3KAVm7Jse3rGITowu0VjgUgNMPbifmY8g

View file

@ -6,7 +6,7 @@ import re
from collections import OrderedDict
from collections.abc import MutableMapping
from enum import Enum, auto
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, override
from typing import overload
@ -60,24 +60,16 @@ class StringTree(MutableMapping): # export
class Error(Exception):
pass
def __init__(
self, path: str, content: str, parent: StringTree | None = None
) -> None:
slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")')
self.__parent: StringTree | None = parent
self.children: OrderedDict[str, StringTree] = OrderedDict()
self.content: str | None = None
self.__set(path, content)
#assert self.content is not None
class Match(Enum):
Equal = auto()
RegExArg = auto()
RegExConf = auto()
GlobArg = auto()
GlobConf = auto()
# root (content = [ symbols ])
# symbols (content = [ regex ])
# regex ( content ='[ \n\t\r]+' )
# root (content = root, children = [ symbols ])
# symbols (content = symbols, children = [ regex ])
# regex ( content = regex, children = [ '[ \n\t\r]+' ] )
# '[ \n\t\r]+)' ( content = '\n\t\r]+)', children = [] )
__parent: StringTree | None
children: OrderedDict[str, StringTree]
content: str | None
def __adopt_children(self, parent: StringTree) -> None:
assert isinstance(parent, StringTree)
@ -178,31 +170,6 @@ class StringTree(MutableMapping): # export
self.children[nibble].children[gc.content] = gc
return self.children[nibble]
def __repr__(self) -> str:
return 'st:"{}"'.format(self.content)
def __str__(self) -> str:
return self.content or ''
def __getitem__(self, path: str) -> StringTree:
ret = self.get(path)
if ret is None:
raise self.Error(path)
return ret
def __setitem__(self, key: str, value: str) -> None:
self.__set(key, value)
def __iter__(self) -> Iterator[str]:
return iter(self.children)
def __delitem__(self, key: str) -> None:
if key in self.children:
del self.children[key]
def __len__(self) -> int:
return len(self.children)
def __dump(self, prio: int, indent: int = 0, **kwargs: Any) -> None:
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
slog(prio, '|' + (' ' * indent) + str(self.content), caller = caller)
@ -210,108 +177,6 @@ class StringTree(MutableMapping): # export
for name, child in self.children.items():
child.__dump(prio, indent = indent, caller = caller)
@property
def path(self) -> str:
if self.__parent is None:
return ''
prefix = self.__parent.path
if len(prefix):
prefix += '.'
return prefix + cast('str', self.content)
def set_content(self, content: str) -> None:
if content is None:
raise self.Error("Tried to set none content")
content = cleanup_string(content)
if len(content) == 0:
raise self.Error("Tried to set empty content")
self.content = content
def add(
self,
path: str,
content: str | StringTree | None = None,
split: bool = True
) -> StringTree:
slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content}"')
return self.__set(path, content, split)
def get(self, path: str, default: Any = None) -> StringTree | None:
slog(DEBUG, 'looking for "{}" in "{}"'.format(path, self.content))
assert not isinstance(path, int)
_path: str = cleanup_string(path)
if len(_path) == 0:
slog(DEBUG, "returning myself")
return self
if is_quoted(path):
if _path not in self.children.keys():
return default
return self.children[_path]
components: list[str] = _path.split('.')
if len(components) == 0:
return self
name: str = cleanup_string(components[0])
if not hasattr(self, "children"):
return default
if name not in self.children.keys():
slog(DEBUG, "Name \"" + name + "\" is not in children of", self.content)
for child in self.children:
slog(DEBUG, "child = ", child)
return default
rel_path: str = '.'.join(components[1:])
return self.children[name].get(rel_path)
def value(self, path: str | None = None, default: str | None = None) -> str | None:
if path:
child = self.get(path)
if child is None:
if default:
return default
return None
return child.value()
if len(self.children) == 0:
raise self.Error('tried to get value from leaf "{}"'.format(self.content))
slog(DEBUG, f'Returning value from children {self.children}')
return self.children[next(reversed(self.children))].content
@property
def parent(self) -> StringTree | None:
return self.__parent
@property
def root(self) -> StringTree:
if self.__parent is None:
return self
return self.__parent.root
def child_list(self, depth_first: bool = True) -> list[StringTree]:
if not depth_first:
raise self.Error(
'Tried to retrieve child list with breadth-first '
'search, not yet implemented'
)
r: list[StringTree] = []
for name, c in self.children.items():
r.append(c)
r.extend(c.child_list())
return r
def dump(self, prio: int, *args: str, **kwargs: Any) -> None:
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
msg: str = ''
if args is not None:
msg = ' ' + ' '.join(args) + ' '
slog(prio, ",------------" + msg + "----------- >", caller = caller)
self.__dump(prio, indent = 0, caller = caller)
slog(prio, "`------------" + msg + "----------- <", caller = caller)
class Match(Enum):
Equal = auto()
RegExArg = auto()
RegExConf = auto()
GlobArg = auto()
GlobConf = auto()
def __find(
self,
key: str | None,
@ -377,6 +242,167 @@ class StringTree(MutableMapping): # export
return ret
@staticmethod
def _dict_to_tree(
parent: StringTree,
data: dict[str, str | Any],
) -> None:
"""Recursively populate *parent* with entries from a nested dict."""
for key, value in data.items():
if isinstance(value, dict):
StringTree._dict_to_tree(parent.add(key), value)
else:
parent.add(key, str(value))
@override
def __repr__(self) -> str:
return 'st:"{}"'.format(self.content)
@override
def __str__(self) -> str:
return self.content or ''
@override
def __getitem__(self, path: str) -> StringTree:
ret = self.get(path)
if ret is None:
raise self.Error(path)
return ret
@override
def __setitem__(self, key: str, value: str) -> None:
self.__set(key, value)
@override
def __iter__(self) -> Iterator[str]:
return iter(self.children)
@override
def __delitem__(self, key: str) -> None:
if key in self.children:
del self.children[key]
@override
def __len__(self) -> int:
return len(self.children)
# -- Public API
def __init__(
self, path: str, content: str, parent: StringTree | None = None
) -> None:
slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")')
self.__parent: StringTree | None = parent
self.children: OrderedDict[str, StringTree] = OrderedDict()
self.content: str | None = None
self.__set(path, content)
#assert self.content is not None
# root (content = [ symbols ])
# symbols (content = [ regex ])
# regex ( content ='[ \n\t\r]+' )
# root (content = root, children = [ symbols ])
# symbols (content = symbols, children = [ regex ])
# regex ( content = regex, children = [ '[ \n\t\r]+' ] )
# '[ \n\t\r]+)' ( content = '\n\t\r]+)', children = [] )
@property
def path(self) -> str:
if self.__parent is None:
return ''
prefix = self.__parent.path
if len(prefix):
prefix += '.'
return prefix + cast('str', self.content)
@property
def parent(self) -> StringTree | None:
return self.__parent
@property
def root(self) -> StringTree:
if self.__parent is None:
return self
return self.__parent.root
def set_content(self, content: str) -> None:
if content is None:
raise self.Error("Tried to set none content")
content = cleanup_string(content)
if len(content) == 0:
raise self.Error("Tried to set empty content")
self.content = content
def add(
self,
path: str,
content: str | StringTree | None = None,
split: bool = True
) -> StringTree:
slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content}"')
return self.__set(path, content, split)
@override
def get(self, path: str, default: Any = None) -> StringTree | None:
slog(DEBUG, 'looking for "{}" in "{}"'.format(path, self.content))
assert not isinstance(path, int)
_path: str = cleanup_string(path)
if len(_path) == 0:
slog(DEBUG, "returning myself")
return self
if is_quoted(path):
if _path not in self.children.keys():
return default
return self.children[_path]
components: list[str] = _path.split('.')
if len(components) == 0:
return self
name: str = cleanup_string(components[0])
if not hasattr(self, "children"):
return default
if name not in self.children.keys():
slog(DEBUG, "Name \"" + name + "\" is not in children of", self.content)
for child in self.children:
slog(DEBUG, "child = ", child)
return default
rel_path: str = '.'.join(components[1:])
return self.children[name].get(rel_path)
def value(self, path: str | None = None, default: str | None = None) -> str | None:
if path:
child = self.get(path)
if child is None:
if default:
return default
return None
return child.value()
if len(self.children) == 0:
raise self.Error('tried to get value from leaf "{}"'.format(self.content))
slog(DEBUG, f'Returning value from children {self.children}')
return self.children[next(reversed(self.children))].content
def child_list(self, depth_first: bool = True) -> list[StringTree]:
if not depth_first:
raise self.Error(
'Tried to retrieve child list with breadth-first '
'search, not yet implemented'
)
r: list[StringTree] = []
for name, c in self.children.items():
r.append(c)
r.extend(c.child_list())
return r
def dump(self, prio: int, *args: str, **kwargs: Any) -> None:
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
msg: str = ''
if args is not None:
msg = ' ' + ' '.join(args) + ' '
slog(prio, ",------------" + msg + "----------- >", caller = caller)
self.__dump(prio, indent = 0, caller = caller)
slog(prio, "`------------" + msg + "----------- <", caller = caller)
def find(
self,
key: str | None = None,
@ -406,3 +432,26 @@ class StringTree(MutableMapping): # export
log_prio = log_prio,
paths_buf = paths_buf
)
@classmethod
def from_dict(
cls,
data: dict[str, str | Any],
root_content: str = 'root',
) -> StringTree:
"""Build a StringTree from a nested dict.
Dict values that are dicts represent sub-trees. All other values
are converted to strings via ``str()``. Keys are path components;
dotted keys are expanded just as with :meth:`add`.
Example::
>>> tree = StringTree.from_dict({'section': {'key': 'value'}})
>>> tree.value('section.key')
'value'
"""
tree: StringTree = cls('', content = root_content)
cls._dict_to_tree(tree, data)
return tree