From e014a9251ffaef9531777965b600e657699de606 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Fri, 24 Jul 2026 22:02:28 +0200 Subject: [PATCH] mypy: Fix disallow_untyped_calls check fallout Add return type annotations and parameter type hints to previously untyped functions, preparing for disallow_untyped_calls enforcement: - ArgsContainer.py: keys() -> Iterable[str] - Object.py: Object.__init__() -> None - ShuntingYard.py: tokenize(), infix_to_postfix(), __init__(), add_operator(), Stack methods, debug(), Calculator/Matcher.__init__() - ShellCmd.py: __exec(), __cleanup(), init(), cleanup(), __init__() - Auth.py: __bind() -> Connection, import Connection - TableIoHandler.py: _check_non_nullable() -> None, buf annotation - Queries.py: _add() -> None - rows.py: __equal(), rows_duplicates(), rows_check_not_null(), rows_dump(), rows_dumps() with proper type signatures - CompositeForeignKey.py: __table() -> Table - EventRouter.py: iter_peers() -> Iterator[tuple[str, Any]] - MapAttr2Shape.py: __value(), __add_key_nodegraphics() - ldap.py: __search() -> str, collect() -> set[str] - multi_key_dict.py: has_key(), get_other_keys(), iterkeys(), get_values_from_str(), test_multi_key_dict(), __init__(), items_dict annotation Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0 Signed-off-by: Jan Lindemann --- src/python/jw/util/ArgsContainer.py | 4 +- src/python/jw/util/Object.py | 2 +- src/python/jw/util/algo/ShuntingYard.py | 43 ++++++++++--------- src/python/jw/util/asyncio/ShellCmd.py | 14 +++--- src/python/jw/util/auth/ldap/Auth.py | 4 +- src/python/jw/util/db/TableIoHandler.py | 7 ++- src/python/jw/util/db/query/Queries.py | 2 +- src/python/jw/util/db/rows.py | 29 +++++++------ .../jw/util/db/schema/CompositeForeignKey.py | 9 ++-- src/python/jw/util/graph/yed/MapAttr2Shape.py | 6 +-- src/python/jw/util/ldap.py | 4 +- src/python/jw/util/multi_key_dict.py | 18 ++++---- 12 files changed, 76 insertions(+), 66 deletions(-) diff --git a/src/python/jw/util/ArgsContainer.py b/src/python/jw/util/ArgsContainer.py index 4ff601e..aa5f94b 100644 --- a/src/python/jw/util/ArgsContainer.py +++ b/src/python/jw/util/ArgsContainer.py @@ -1,5 +1,5 @@ import argparse -from typing import override +from typing import Iterable, override from collections import OrderedDict @@ -43,7 +43,7 @@ class ArgsContainer: # export self.__args[name] = arg self.__kwargs[name] = kwargs - def keys(self): + def keys(self) -> Iterable[str]: return self.__args.keys() def args(self, name) -> str: diff --git a/src/python/jw/util/Object.py b/src/python/jw/util/Object.py index fb09f60..5274abe 100644 --- a/src/python/jw/util/Object.py +++ b/src/python/jw/util/Object.py @@ -17,7 +17,7 @@ class Object(abc.ABC): raise TypeError("Expected a super() proxy") return f"{owner.__module__}.{owner.__qualname__}" - def __init__(self): + def __init__(self) -> None: self.log_level = log.log_level() @override diff --git a/src/python/jw/util/algo/ShuntingYard.py b/src/python/jw/util/algo/ShuntingYard.py index 426f49c..b1838cc 100644 --- a/src/python/jw/util/algo/ShuntingYard.py +++ b/src/python/jw/util/algo/ShuntingYard.py @@ -1,5 +1,5 @@ import re -from typing import cast, override +from typing import Any, cast, override from collections import namedtuple @@ -10,7 +10,7 @@ ARG, KEYW, QUOTED, LPAREN, RPAREN = 'arg kw quoted ( )'.split() class Operator: # export - def __init__(self, func = None, nargs = 2, precedence = 3, assoc = L): + def __init__(self, func = None, nargs: int = 2, precedence: int = 3, assoc = L): self.func = func self.nargs = nargs self.prec = precedence @@ -18,7 +18,7 @@ class Operator: # export class Stack: - def __init__(self, itemlist = []): + def __init__(self, itemlist: list[Any] = []): self.items = itemlist @override @@ -33,23 +33,23 @@ class Stack: def peek(self): return self.items[-1:][0] - def pop(self): + def pop(self) -> Any: return self.items.pop() - def push(self, item): + def push(self, item: Any) -> int: self.items.append(item) return 0 class ShuntingYard(object): # export - def __init__(self, operators = None): + def __init__(self, operators: dict[str, Any] | None = None): self.do_debug = prio_gets_logged(DEBUG) - self.__ops = {} + self.__ops: dict[str, Operator] = {} if operators is not None: for k, v in operators.items(): self.add_operator(k, v.func, v.nargs, v.prec, v.assoc) - def debug(self, *args): + def debug(self, *args: Any) -> None: if self.do_debug: msg = "" for count, thing in enumerate(args): @@ -58,7 +58,7 @@ class ShuntingYard(object): # export slog(DEBUG, msg[1:], caller = get_caller_pos()) def operator(self, key: str) -> Operator: - return cast('Operator', self.__ops[key]) + return self.__ops[key] def token_string(self): r = "" @@ -76,7 +76,7 @@ class ShuntingYard(object): # export return r[2:] return r - def tokenize(self, spec): + def tokenize(self, spec) -> list[tuple[str, Any]]: regex = "" for k in self.__ops.keys(): @@ -84,7 +84,7 @@ class ShuntingYard(object): # export regex = regex[1:] - scanner = re.Scanner( # pyright: ignore[reportAttributeAccessIssue] + scanner = re.Scanner( # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] [ (regex, lambda scanner, token: (KEYW, token)), (r"\"[^\"]*\"|'[^']*'", lambda scanner, token: (QUOTED, token[1:-1])), @@ -100,7 +100,7 @@ class ShuntingYard(object): # export ) #self.debug(tokens) - return tokens + return cast(list[tuple[str, Any]], tokens) r = [] for e in tokens: if e[0] == "quoted": @@ -110,14 +110,15 @@ class ShuntingYard(object): # export return r - def add_operator(self, name, func, nargs, precedence, assoc): + def add_operator(self, name: str, func: Any, nargs: int, precedence: int, assoc: Any) -> None: self.__ops[name] = Operator(func, nargs, precedence, assoc) - def infix_to_postfix(self, infix): + def infix_to_postfix(self, infix) -> list[str]: tokenized = self.tokenize(infix) self.debug("tokenized = ", tokenized) - outq, stack = [], [] - table = ['TOKEN', 'ACTION', 'RPN OUTPUT', ('OP STACK', ), 'NOTES'] + outq: list[str] = [] + stack: list[Any] = [] + table: list[Any] = ['TOKEN', 'ACTION', 'RPN OUTPUT', ('OP STACK', ), 'NOTES'] for toktype, token in tokenized: self.debug("Checking token", token) note = action = '' @@ -195,7 +196,7 @@ class ShuntingYard(object): # export for (width, cell) in zip(maxcolwidths, row) ) ) - return table[-1][2] + return cast(list[str], table[-1][2]) def infix_to_postfix_orig(self, infix): @@ -242,7 +243,7 @@ class ShuntingYard(object): # export return r #return " ".join(r) - def eval_postfix(self, postfixexpr): + def eval_postfix(self, postfixexpr) -> Any: self.debug("postfix = ", postfixexpr) vals = Stack() @@ -269,7 +270,7 @@ class ShuntingYard(object): # export return vals.pop() - def eval(self, infix): + def eval(self, infix) -> Any: if not isinstance(infix, str): return infix postfix = self.infix_to_postfix(infix) @@ -301,7 +302,7 @@ if __name__ == '__main__': def f_sub(self, a, b): return str(atof(a) - atof(b)) - def __init__(self): + def __init__(self) -> None: Op = Operator operators = { '^': Op(None, 2, 4, R), @@ -345,7 +346,7 @@ if __name__ == '__main__': return "True" return "False" - def __init__(self, obj): + def __init__(self, obj) -> None: Op = Operator operators = { '(': Op(None, 2, 9, L), diff --git a/src/python/jw/util/asyncio/ShellCmd.py b/src/python/jw/util/asyncio/ShellCmd.py index 648ac06..d1d0806 100644 --- a/src/python/jw/util/asyncio/ShellCmd.py +++ b/src/python/jw/util/asyncio/ShellCmd.py @@ -36,7 +36,7 @@ class ShellCmd: # export Completed = 3 Unnecessary = 4 - def __init__(self, cmdline, eloop = None, name = None): + def __init__(self, cmdline: list[str], eloop = None, name = None) -> None: if eloop is None: eloop = asyncio.get_running_loop() self.__eloop = eloop @@ -49,7 +49,7 @@ class ShellCmd: # export self.__task = None self.__shutdown = self.ShutdownState.Unnecessary - async def __exec(self): + async def __exec(self) -> None: def format_cmdline(arr): r = '' @@ -89,7 +89,7 @@ class ShellCmd: # export slog(DEBUG, "Process {} exited".format(self.__name)) self.__reap() - async def __cleanup(self): + async def __cleanup(self) -> None: pid = self.__reap() sd_fine = self.__shutdown in [ self.ShutdownState.Unnecessary, self.ShutdownState.Completed @@ -111,13 +111,13 @@ class ShellCmd: # export ) exit(1) - async def init(self): + async def init(self) -> None: self.__task = await self.__eloop.create_task(self.__exec()) - async def cleanup(self): + async def cleanup(self) -> None: await self.__cleanup() - async def run(self): + async def run(self) -> None: await self.init() await self.cleanup() @@ -125,7 +125,7 @@ if __name__ == '__main__': from .. import log log.set_level('info') - async def run(): + async def run() -> None: sp = ShellCmd(['echo', 'hello world!']) await sp.run() diff --git a/src/python/jw/util/auth/ldap/Auth.py b/src/python/jw/util/auth/ldap/Auth.py index b80d85d..e6814d3 100644 --- a/src/python/jw/util/auth/ldap/Auth.py +++ b/src/python/jw/util/auth/ldap/Auth.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, override import ldap # type: ignore[import-untyped] -from ...ldap import bind +from ...ldap import bind, Connection from ...log import DEBUG, ERR, WARNING, slog from ..Auth import Access from ..Auth import Auth as AuthBase @@ -81,7 +81,7 @@ class Auth(AuthBase): # export self.__conn = self.__bind() self.__dummy = AuthBase.load(conf, tp = 'dummy') - def __bind(self): + def __bind(self) -> Connection: return bind(self.conf) @property diff --git a/src/python/jw/util/db/TableIoHandler.py b/src/python/jw/util/db/TableIoHandler.py index a6bcd25..3cd4590 100644 --- a/src/python/jw/util/db/TableIoHandler.py +++ b/src/python/jw/util/db/TableIoHandler.py @@ -33,8 +33,8 @@ class TableIoHandler(ABC): # export def _primary_keys(self): return self._table_meta.primary_keys - def _check_non_nullable(self, rows): - buf = [] + def _check_non_nullable(self, rows: list[dict[str, Any]]) -> None: + buf: list[dict[str, Any]] = [] non_nullable = self._table_meta.not_null_insertible_columns try: rows_check_not_null(rows, non_nullable, buf = buf) @@ -77,6 +77,9 @@ class TableIoHandler(ABC): # export ) -> TType: slog(INFO, f'Reading table "{self._table_name}" from "{uri}"') ret = self._load(uri, reference) + if check_duplicates: + slog(INFO, f'Checking duplicates in {self._table_name}') + d = rows_duplicates(ret) if check_duplicates: slog(INFO, f'Checking duplicates in {self._table_name}') d = rows_duplicates(ret) diff --git a/src/python/jw/util/db/query/Queries.py b/src/python/jw/util/db/query/Queries.py index 2e3f61f..64c282b 100644 --- a/src/python/jw/util/db/query/Queries.py +++ b/src/python/jw/util/db/query/Queries.py @@ -81,5 +81,5 @@ class Queries(abc.ABC): # export self._add(ret) # To be overriden in case the derived class wants to keep track - def _add(self, query): + def _add(self, query) -> None: pass diff --git a/src/python/jw/util/db/rows.py b/src/python/jw/util/db/rows.py index b7094cc..85b6428 100644 --- a/src/python/jw/util/db/rows.py +++ b/src/python/jw/util/db/rows.py @@ -5,6 +5,8 @@ import os import re import textwrap +from typing import Any + from tabulate import TableFormat, tabulate # type: ignore[import-untyped] from ..log import (ERR, INFO, WARNING, get_caller_pos, prio_gets_logged, slog, slog_m) @@ -17,9 +19,9 @@ def rows_pretty(rows): # export out.append(json.dumps(row, sort_keys = True, indent = 4, default = str)) return '\n'.join(out) -def rows_duplicates(rows, log_prio = INFO, caller = None): # export +def rows_duplicates(rows, log_prio = INFO, caller = None) -> list[int]: # export - def __equal(r1, r2): + def __equal(r1: dict[str, Any], r2: dict[str, Any]) -> bool: for col in set(r1.keys()) | set(r2.keys()): if col in r1: if col not in r2: @@ -112,20 +114,20 @@ def rows_rewrite_regex(rows, rules): # export raise def rows_check_not_null( # export - rows, + rows: list[dict[str, Any]], keys, log_prio = WARNING, - buf = None, + buf: list[dict[str, Any]] | None = None, stat_key = None, - throw = True, + throw: bool = True, caller = None -): +) -> list[dict[str, Any]]: if isinstance(keys, str): keys = [keys] if caller is None: caller = get_caller_pos() count = 0 - stats = dict() + stats: dict[str, int] = dict() if buf is None: buf = [] else: @@ -165,7 +167,7 @@ def rows_dumps( # export heading = None, lead = None, tablefmt = None -): +) -> str: headers = 'keys' dump_rows = rows @@ -244,9 +246,12 @@ def rows_dumps( # export lead = '' assert isinstance(tablefmt, str) or isinstance(tablefmt, TableFormat), 'tablefmt' - return header + heading + lead + tabulate( - dump_rows, headers = headers, tablefmt = tablefmt - ) + footer + return cast( + str, + header + heading + lead + tabulate( + dump_rows, headers = headers, tablefmt = tablefmt + ) + footer + ) def rows_dump( # export rows, @@ -259,7 +264,7 @@ def rows_dump( # export heading = None, lead = None, tablefmt = None -): +) -> None: if not prio_gets_logged(log_prio): return diff --git a/src/python/jw/util/db/schema/CompositeForeignKey.py b/src/python/jw/util/db/schema/CompositeForeignKey.py index 16637f9..4697d6a 100644 --- a/src/python/jw/util/db/schema/CompositeForeignKey.py +++ b/src/python/jw/util/db/schema/CompositeForeignKey.py @@ -1,12 +1,13 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional, override +from typing import TYPE_CHECKING, Any, Optional, cast, override from ...log import WARNING, slog from .SingleForeignKey import SingleForeignKey if TYPE_CHECKING: from .ColumnSet import ColumnSet + from .Table import Table class CompositeForeignKey: # export @@ -14,11 +15,11 @@ class CompositeForeignKey: # export self, child_col_set: ColumnSet, parent_col_set: ColumnSet ): # TODO: Implement alternative ways to construct - def __table(s): - ret = None + def __table(s) -> Table: + ret: Table | None = None for c in s: if ret is None: - ret = c.table + ret = cast(Table, c.table) else: assert (ret == c.table) assert (ret is not None) diff --git a/src/python/jw/util/graph/yed/MapAttr2Shape.py b/src/python/jw/util/graph/yed/MapAttr2Shape.py index 2d8b9be..455b660 100644 --- a/src/python/jw/util/graph/yed/MapAttr2Shape.py +++ b/src/python/jw/util/graph/yed/MapAttr2Shape.py @@ -2,7 +2,7 @@ from __future__ import annotations import xml.etree.ElementTree as ET -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Callable @@ -44,7 +44,7 @@ class MapAttr2Shape: # export ret[attr_name] = id return ret - def __value(self, node, key): + def __value(self, node: ET.Element, key: str) -> str | None: data = node.find(f'data[@key="{key}"]', self.__ns) if data is None: return None @@ -59,7 +59,7 @@ class MapAttr2Shape: # export ret[name] = val return ret - def __add_key_nodegraphics(self, root): + def __add_key_nodegraphics(self, root: ET.Element) -> None: # el = ET.Element('key') for attr, val in { diff --git a/src/python/jw/util/ldap.py b/src/python/jw/util/ldap.py index 6ff94e7..538b75b 100644 --- a/src/python/jw/util/ldap.py +++ b/src/python/jw/util/ldap.py @@ -239,7 +239,7 @@ class Connection: # export def __walk_cb_find(conn: Connection, entry: Any, context: Any): result.append(entry) - def __search(): + def __search() -> str: return f'{base} -> "{filterstr}"' try: @@ -326,7 +326,7 @@ class Connection: # export if self.__object_class_tree is None: - def collect(root, attr): + def collect(root: str, attr: str) -> set[str]: ret = set() def cb(oc, attr): diff --git a/src/python/jw/util/multi_key_dict.py b/src/python/jw/util/multi_key_dict.py index 4600343..59e62a2 100644 --- a/src/python/jw/util/multi_key_dict.py +++ b/src/python/jw/util/multi_key_dict.py @@ -79,10 +79,10 @@ class multi_key_dict(object): print k[1000] # will print 'kilo' as value was updated """ - def __init__(self, mapping_or_iterable = None, **kwargs): + def __init__(self, mapping_or_iterable: Any = None, **kwargs: Any) -> None: """ Initializes dictionary from an optional positional argument and a possibly empty set of keyword arguments.""" - self.items_dict = {} + self.items_dict: dict[str, Any] = {} if mapping_or_iterable is not None: if type(mapping_or_iterable) is dict: mapping_or_iterable = mapping_or_iterable.items() @@ -181,11 +181,11 @@ class multi_key_dict(object): return False - def has_key(self, key): + def has_key(self, key: Any) -> bool: """ Returns True if this object contains an item referenced by the key.""" return key in self - def get_other_keys(self, key, including_current = False): + def get_other_keys(self, key: Any, including_current: bool = False) -> list[Any]: """ Returns list of other keys that are mapped to the same value as specified key. @param key - key for which other keys should be returned. @param including_current if set to True - key will also appear on this list.""" @@ -196,7 +196,7 @@ class multi_key_dict(object): other_keys.remove(key) return other_keys - def iteritems(self, key_type = None, return_all_keys = False): + def iteritems(self, key_type: Any = None, return_all_keys: bool = False) -> Any: """ Returns an iterator over the dictionary's (key, value) pairs. @param key_type if specified, iterator will be returning only (key,value) @@ -224,7 +224,7 @@ class multi_key_dict(object): keys = tuple(k for k in keys if isinstance(k, key_type)) yield keys, value - def iterkeys(self, key_type = None, return_all_keys = False): + def iterkeys(self, key_type: Any = None, return_all_keys: bool = False) -> Any: """ Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. @@ -353,7 +353,7 @@ class multi_key_dict(object): dict_str = '{%s}' % (', '.join(items)) return dict_str -def test_multi_key_dict(): +def test_multi_key_dict() -> None: def contains_all(cont, in_items): return False not in [c in cont for c in in_items] @@ -429,8 +429,8 @@ def test_multi_key_dict(): ), ('str(m) should end with \'}\', but does with \'%c\'' % m_str[-1]) # check if all key-values are there as expected. They might be sorted differently - def get_values_from_str(dict_str): - sorted_keys_and_values = [] + def get_values_from_str(dict_str: str) -> list[tuple[tuple[str, ...], str]]: + sorted_keys_and_values: list[tuple[tuple[str, ...], str]] = [] for k in dict_str.split(', ('): keys, val = k.strip('{}() ').replace(')', '').split(':') keys = tuple(sorted([k.strip() for k in keys.split(',')]))