From 4d49b508bc4e44839dc67e8be7a81818d1f0b016 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Mon, 13 Jul 2026 13:19:10 +0200 Subject: [PATCH] stree: Type annotate StringTree and serdes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The StringTree class and its companion serdes module have minimal type annotations — only method signatures and a few instance attributes were typed. This commit adds proper type annotations to every parameter, return type, and local variable across both files. cleanup_string() gains overloaded signatures so callers passing str get str back, avoiding the need to widen the return type everywhere. The matcher return type in __find is narrowed from Any to Callable[[str, str], bool]. Casts are used sparingly where the runtime guarantees a narrower type than the checker can infer (e.g. self.value() always returns str when called without path, despite the return annotation being str | None). Variable annotations in StringTree.__set, get, __find, child_list, and dump cover local bindings. serdes gains full parameter and return type coverage plus annotations for all local variables in _cleanup_line, parse, _read_lines_from_one_path, and _read_lines. The get() default parameter remains Any because overriding Mapping.get with a concrete type breaks the Liskov substitution principle — Mapping.get is generic over the default type. Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.80.2 Signed-off-by: Jan Lindemann --- src/python/jw/util/stree/StringTree.py | 71 +++++++++++++++----------- src/python/jw/util/stree/serdes.py | 50 ++++++++++-------- 2 files changed, 70 insertions(+), 51 deletions(-) diff --git a/src/python/jw/util/stree/StringTree.py b/src/python/jw/util/stree/StringTree.py index 3134607..d196a28 100644 --- a/src/python/jw/util/stree/StringTree.py +++ b/src/python/jw/util/stree/StringTree.py @@ -10,7 +10,10 @@ from typing import TYPE_CHECKING from typing import overload +from typing import cast + if TYPE_CHECKING: + from collections.abc import Callable from typing import Any, Iterator from ..log import DEBUG, INFO, get_caller_pos, slog @@ -61,7 +64,7 @@ class StringTree(Mapping): # export self, path: str, content: str, parent: StringTree | None = None ) -> None: slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")') - self.__parent = parent + self.__parent: StringTree | None = parent self.children: OrderedDict[str, StringTree] = OrderedDict() self.content: str | None = None self.__set(path, content) @@ -89,7 +92,10 @@ class StringTree(Mapping): # export self.children[name].__adopt_children(c) def __set( - self, path: str, content: str | StringTree | None, split = True + self, + path: str, + content: str | StringTree | None, + split: bool = True ) -> StringTree: slog( DEBUG, @@ -124,7 +130,7 @@ class StringTree(Mapping): # export str(self.content) + "<" ) return self - _path = cleanup_string(path) + _path: str = cleanup_string(path) if not _path: #assert self.content is None or ( @@ -146,12 +152,12 @@ class StringTree(Mapping): # export #self.children[content] = StringTree(None, content) return self - components = _path.split('.') if split else [_path] - length = len(components) + components: list[str] = _path.split('.') if split else [_path] + length: int = len(components) #assert self.content is not None, f'Tried to set empty content to "{path}"' - nibble = components[0] - rest = '.'.join(components[1:]) + nibble: str = components[0] + rest: str = '.'.join(components[1:]) if nibble not in self.children: self.children[nibble] = StringTree('', content = nibble, parent = self) if length > 1: @@ -160,7 +166,7 @@ class StringTree(Mapping): # export return self.children[nibble].__set(rest, content = content) # last component, a.k.a. leaf if content is not None: - gc = content if isinstance(content, StringTree) else StringTree( + gc: StringTree = content if isinstance(content, StringTree) else StringTree( '', content = content, parent = self.children[nibble] ) if gc.content is None: @@ -193,7 +199,7 @@ class StringTree(Mapping): # export def __len__(self) -> int: return len(self.children) - def __dump(self, prio, indent = 0, **kwargs): + 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) indent += 2 @@ -201,15 +207,15 @@ class StringTree(Mapping): # export child.__dump(prio, indent = indent, caller = caller) @property - def path(self): + def path(self) -> str: if self.__parent is None: return '' prefix = self.__parent.path if len(prefix): prefix += '.' - return prefix + self.content + return prefix + cast('str', self.content) - def set_content(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) @@ -226,10 +232,10 @@ class StringTree(Mapping): # export slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content}"') return self.__set(path, content, split) - def get(self, path: str, default = None) -> StringTree | None: + 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 = cleanup_string(path) + _path: str = cleanup_string(path) if len(_path) == 0: slog(DEBUG, "returning myself") return self @@ -237,10 +243,10 @@ class StringTree(Mapping): # export if _path not in self.children.keys(): return default return self.children[_path] - components = _path.split('.') + components: list[str] = _path.split('.') if len(components) == 0: return self - name = cleanup_string(components[0]) + name: str = cleanup_string(components[0]) if not hasattr(self, "children"): return default if name not in self.children.keys(): @@ -248,7 +254,7 @@ class StringTree(Mapping): # export for child in self.children: slog(DEBUG, "child = ", child) return default - rel_path = '.'.join(components[1:]) + 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: @@ -280,15 +286,15 @@ class StringTree(Mapping): # export 'Tried to retrieve child list with breadth-first ' 'search, not yet implemented' ) - r = [] + 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, **kwargs) -> None: + def dump(self, prio: int, *args: str, **kwargs: Any) -> None: caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1) - msg = '' + msg: str = '' if args is not None: msg = ' ' + ' '.join(args) + ' ' slog(prio, ",------------" + msg + "----------- >", caller = caller) @@ -310,22 +316,22 @@ class StringTree(Mapping): # export depth_first: bool, ) -> list[StringTree]: - def __children(): + def __children() -> None: for name, child in self.children.items(): ret.extend(child.__find(key, val, m, depth_first)) - def __self(): - _val = self.value() - _content = self.content + def __self() -> None: + _val: str = cast('str', self.value()) + _content: str | None = self.content try: - if ((key == _content and matcher(val, _val)) - or (key is None and matcher(val, _val)) + if ((key == _content and matcher(cast('str', val), _val)) + or (key is None and matcher(cast('str', val), _val)) or (key == _content and val is None)): ret.append(self) except Exception as e: raise self.Error(str(e)).with_traceback(e.__traceback__) from e - def __select_matcher(m: StringTree.Match) -> Any: + def __select_matcher(m: StringTree.Match) -> Callable[[str, str], bool]: match m: case self.Match.Equal: return lambda x, y: x == y @@ -340,9 +346,12 @@ class StringTree(Mapping): # export case _: raise NotImplementedError(f'Matcher {m} is not yet implemented') - def __debug_matcher(matcher, log_level = DEBUG): + def __debug_matcher( + matcher: Callable[[str, str], bool], + log_level: int = DEBUG + ) -> Callable[[str, str], bool]: - def __matcher(x, y): + def __matcher(x: str, y: str) -> bool: slog(log_level, f'Comparing "{x}" ~ "{y}"') return matcher(x, y) @@ -383,8 +392,8 @@ class StringTree(Mapping): # export cls, path: str, root_content: str = 'root', - log_prio = INFO, - paths_buf = None + log_prio: int = INFO, + paths_buf: list[str] | None = None ) -> StringTree: from .serdes import read return read( diff --git a/src/python/jw/util/stree/serdes.py b/src/python/jw/util/stree/serdes.py index 8be6287..10d3089 100644 --- a/src/python/jw/util/stree/serdes.py +++ b/src/python/jw/util/stree/serdes.py @@ -7,8 +7,8 @@ from .StringTree import StringTree, cleanup_string def _cleanup_line(line: str) -> str: line = line.strip() - r = '' - in_quote = None + r: str = '' + in_quote: str | None = None for c in line: # slog(DEBUG, "in_quote = >" + str(in_quote) + "<") if in_quote is not None: @@ -31,7 +31,7 @@ def parse( # export ) -> StringTree: slog_m(DEBUG, "--->--- parsing --->---\n" + s + "\n---<--- parsing ---<---\n") root = StringTree('', content = root_content) - sec = '' + sec: str = '' for line in s.splitlines(): slog(DEBUG, f'Parsing: "{line}"') line = _cleanup_line(line) @@ -54,8 +54,8 @@ def parse( # export assert (len(sec) > 0) sec = '.'.join(sec.split('.')[0:-1]) continue - lhs = '' - rhs = None + lhs: str = '' + rhs: str | None = None for c in line: if rhs is None: if c == '=': @@ -75,24 +75,28 @@ def parse( # export return root def _read_lines_from_one_path( - path: str, throw = True, level = 0, log_prio = INFO, paths_buf = None -): + path: str, + throw: bool = True, + level: int = 0, + log_prio: int = INFO, + paths_buf: list[str] | None = None +) -> list[str] | None: try: with open(path, 'r') as infile: slog(log_prio, 'Reading {}"{}"'.format(' ' * level * 2, path)) if paths_buf is not None: paths_buf.append(path) - ret = [] - for line in infile: # lines are all trailed by \n - m = re.search(r'^\s*(-)*include\s+(\S+)', line) + ret: list[str] = [] + for line in infile: # lines are all trailed by \n # type: str + m: re.Match | None = re.search(r'^\s*(-)*include\s+(\S+)', line) if m: - optional = m.group(1) == '-' - include_path = m.group(2) + optional: bool = m.group(1) == '-' + include_path: str = m.group(2) if include_path[0] != '/': - dir_name = os.path.dirname(path) + dir_name: str = os.path.dirname(path) if len(dir_name): include_path = dir_name + '/' + include_path - include_lines = _read_lines( + include_lines: list[str] | None = _read_lines( include_path, throw = (not optional), level = level + 1, @@ -111,11 +115,17 @@ def _read_lines_from_one_path( raise return None -def _read_lines(path: str, throw = True, level = 0, log_prio = INFO, paths_buf = None): - paths = glob.glob(path) - ret = [] +def _read_lines( + path: str, + throw: bool = True, + level: int = 0, + log_prio: int = INFO, + paths_buf: list[str] | None = None +) -> list[str] | None: + paths: list[str] = glob.glob(path) + ret: list[str] = [] for p in paths: - rr = _read_lines_from_one_path( + rr: list[str] | None = _read_lines_from_one_path( p, throw = throw, level = level, log_prio = log_prio, paths_buf = paths_buf ) if rr is None: @@ -126,8 +136,8 @@ def _read_lines(path: str, throw = True, level = 0, log_prio = INFO, paths_buf = def read( # export path: str, root_content: str = 'root', - log_prio = INFO, - paths_buf = None + log_prio: int = INFO, + paths_buf: list[str] | None = None ) -> StringTree: lines = _read_lines_from_one_path(path, log_prio = log_prio, paths_buf = paths_buf) if lines is None: