From 4fda12ce6aec8b18789374fc907c12dfd2523ec0 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Fri, 24 Jul 2026 22:20:48 +0200 Subject: [PATCH] mypy: Fix disallow_untyped_calls type errors Add return type annotations and fix type mismatches to satisfy disallow_untyped_calls: - ShuntingYard.py: Operator.func -> Any|None, add assert for None - ShellCmd.py: format_cmdline, __reap, __exec, __cleanup, SubprocessProtocol.__init__ return types, fix unreachable code - TableIoHandler.py: cast _load() return to List[Dict[str, Any]] - rows.py: add cast import, cast rows_dumps() return - CompositeForeignKey.py: __table() cast fix, remove TYPE_CHECKING - ldap.py: collect() parameter type ObjectClass - multi_key_dict.py: get(), itervalues(), test function types, fix variable name conflicts, add set[Any] annotations 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/algo/ShuntingYard.py | 19 ++--- src/python/jw/util/asyncio/ShellCmd.py | 30 +++---- src/python/jw/util/db/TableIoHandler.py | 7 +- src/python/jw/util/db/rows.py | 9 +- .../jw/util/db/schema/CompositeForeignKey.py | 6 +- src/python/jw/util/ldap.py | 2 +- src/python/jw/util/multi_key_dict.py | 85 +++++++++++-------- 7 files changed, 80 insertions(+), 78 deletions(-) diff --git a/src/python/jw/util/algo/ShuntingYard.py b/src/python/jw/util/algo/ShuntingYard.py index b1838cc..1c01dc3 100644 --- a/src/python/jw/util/algo/ShuntingYard.py +++ b/src/python/jw/util/algo/ShuntingYard.py @@ -11,7 +11,7 @@ ARG, KEYW, QUOTED, LPAREN, RPAREN = 'arg kw quoted ( )'.split() class Operator: # export def __init__(self, func = None, nargs: int = 2, precedence: int = 3, assoc = L): - self.func = func + self.func: Any | None = func self.nargs = nargs self.prec = precedence self.assoc = assoc @@ -100,17 +100,11 @@ class ShuntingYard(object): # export ) #self.debug(tokens) - return cast(list[tuple[str, Any]], tokens) - r = [] - for e in tokens: - if e[0] == "quoted": - r.append(e[1][1:-1]) - else: - r.append(e[1]) + return cast('list[tuple[str, Any]]', tokens) - return r - - def add_operator(self, name: str, func: Any, nargs: int, precedence: int, assoc: Any) -> None: + 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) -> list[str]: @@ -196,7 +190,7 @@ class ShuntingYard(object): # export for (width, cell) in zip(maxcolwidths, row) ) ) - return cast(list[str], table[-1][2]) + return cast('list[str]', table[-1][2]) def infix_to_postfix_orig(self, infix): @@ -262,6 +256,7 @@ class ShuntingYard(object): # export self.debug("Adding argument %d" % (i)) args.append(vals.pop()) #self.debug("running %s(%s)" % (token, ', '.join(reversed(args)))) + assert op.func is not None val = op.func(*reversed(args)) self.debug( "%s(%s) = %s" % (token, ', '.join(map(str, reversed(args))), val) diff --git a/src/python/jw/util/asyncio/ShellCmd.py b/src/python/jw/util/asyncio/ShellCmd.py index d1d0806..a4916f7 100644 --- a/src/python/jw/util/asyncio/ShellCmd.py +++ b/src/python/jw/util/asyncio/ShellCmd.py @@ -1,6 +1,6 @@ import asyncio import re -from typing import override +from typing import Any, override from ..log import DEBUG, ERR, INFO, WARNING, slog @@ -10,7 +10,7 @@ class ShellCmd: # export class SubprocessProtocol(asyncio.SubprocessProtocol): - def __init__(self, process, name): + def __init__(self, process: Any, name: str) -> None: self.process = process self.name = name super().__init__() @@ -51,7 +51,7 @@ class ShellCmd: # export async def __exec(self) -> None: - def format_cmdline(arr): + def format_cmdline(arr: list[str]) -> str: r = '' for tok in arr: if re.search(' ', tok): @@ -67,22 +67,23 @@ class ShellCmd: # export self.__name, format_cmdline(self.__cmdline) ) ) - self.__transport, self.__protocol = await self.__eloop.subprocess_exec( + transport, protocol = await self.__eloop.subprocess_exec( lambda: self.SubprocessProtocol(self, self.__name), *self.__cmdline, ) - self.__proc = self.__transport.get_extra_info( - 'subprocess' - ) # Popen instance + self.__transport = transport + self.__protocol = protocol + self.__proc = transport.get_extra_info('subprocess') # Popen instance except: slog(ERR, "Failed to run process [{}]".format(self.__name)) raise - def __reap(self): - if self.__rc is None and self.__transport: - self.__transport = None + def __reap(self) -> int | None: + if self.__rc is None and self.__transport is not None: + self.__transport = None # type: ignore[unreachable] if self.__proc is not None: self.__rc = self.__proc.wait() + return self.__rc # to be called from SubprocessProtocol / SIGCHLD handler def exited(self): @@ -90,24 +91,23 @@ class ShellCmd: # export self.__reap() async def __cleanup(self) -> None: - pid = self.__reap() + rc = self.__reap() sd_fine = self.__shutdown in [ self.ShutdownState.Unnecessary, self.ShutdownState.Completed ] - if self.__rc == 0 and sd_fine: + if rc == 0 and sd_fine: assert self.__proc is not None - slog( + slog( # type: ignore[unreachable] INFO, "The shell command [{}], pid {}, has exited cleanly".format( self.__name, self.__proc.pid ) ) self.monitor = self.console = self.__protocol = self.__task = None - return 0 slog( ERR, "The process ([{}], pid {}) has exited {}with status code {}, aborting". - format(self.__name, pid, "" if sd_fine else "prematurely ", self.__rc) + format(self.__name, rc, "" if sd_fine else "prematurely ", self.__rc) ) exit(1) diff --git a/src/python/jw/util/db/TableIoHandler.py b/src/python/jw/util/db/TableIoHandler.py index 3cd4590..e82724a 100644 --- a/src/python/jw/util/db/TableIoHandler.py +++ b/src/python/jw/util/db/TableIoHandler.py @@ -1,7 +1,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any, Dict, Union +from typing import TYPE_CHECKING, Any, Dict, List, Union, cast from ..log import ERR, INFO, OFF, slog, slog_m from .rows import rows_check_not_null, rows_dump, rows_duplicates @@ -76,10 +76,7 @@ class TableIoHandler(ABC): # export self, uri: str, reference, check_duplicates = False, write_csv = None ) -> 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) + ret = cast('List[Dict[str, Any]]', self._load(uri, reference)) if check_duplicates: slog(INFO, f'Checking duplicates in {self._table_name}') d = rows_duplicates(ret) diff --git a/src/python/jw/util/db/rows.py b/src/python/jw/util/db/rows.py index 85b6428..630f661 100644 --- a/src/python/jw/util/db/rows.py +++ b/src/python/jw/util/db/rows.py @@ -5,7 +5,7 @@ import os import re import textwrap -from typing import Any +from typing import Any, cast from tabulate import TableFormat, tabulate # type: ignore[import-untyped] @@ -247,10 +247,9 @@ def rows_dumps( # export assert isinstance(tablefmt, str) or isinstance(tablefmt, TableFormat), 'tablefmt' return cast( - str, - header + heading + lead + tabulate( - dump_rows, headers = headers, tablefmt = tablefmt - ) + footer + 'str', + header + heading + lead + + tabulate(dump_rows, headers = headers, tablefmt = tablefmt) + footer ) def rows_dump( # export diff --git a/src/python/jw/util/db/schema/CompositeForeignKey.py b/src/python/jw/util/db/schema/CompositeForeignKey.py index 4697d6a..ee4fc8e 100644 --- a/src/python/jw/util/db/schema/CompositeForeignKey.py +++ b/src/python/jw/util/db/schema/CompositeForeignKey.py @@ -15,11 +15,11 @@ class CompositeForeignKey: # export self, child_col_set: ColumnSet, parent_col_set: ColumnSet ): # TODO: Implement alternative ways to construct - def __table(s) -> Table: - ret: Table | None = None + def __table(s) -> 'Table': + ret: 'Table | None' = None for c in s: if ret is None: - ret = cast(Table, c.table) + ret = cast('Table', c.table) else: assert (ret == c.table) assert (ret is not None) diff --git a/src/python/jw/util/ldap.py b/src/python/jw/util/ldap.py index 538b75b..14ee82a 100644 --- a/src/python/jw/util/ldap.py +++ b/src/python/jw/util/ldap.py @@ -326,7 +326,7 @@ class Connection: # export if self.__object_class_tree is None: - def collect(root: str, attr: str) -> set[str]: + def collect(root: ObjectClass, 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 59e62a2..4390c65 100644 --- a/src/python/jw/util/multi_key_dict.py +++ b/src/python/jw/util/multi_key_dict.py @@ -82,7 +82,7 @@ class multi_key_dict(object): 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: dict[str, Any] = {} + self.items_dict: dict[Any, Any] = {} if mapping_or_iterable is not None: if type(mapping_or_iterable) is dict: mapping_or_iterable = mapping_or_iterable.items() @@ -244,7 +244,7 @@ class multi_key_dict(object): for keys in self.items_dict.keys(): yield keys - def itervalues(self, key_type = None): + def itervalues(self, key_type: Any = None) -> Any: """ Returns an iterator over the dictionary's values. @param key_type if specified, iterator will be returning only values pointed by keys of this type. @@ -332,7 +332,7 @@ class multi_key_dict(object): self.items_dict = dict() self.items_dict[direct_key] = item - def get(self, key, default = None): + def get(self, key: Any, default: Any = None) -> Any: """ Return the value at index specified as key.""" if key in self: return self.items_dict[self.__dict__[str(type(key))][key]] @@ -360,7 +360,7 @@ def test_multi_key_dict() -> None: m = multi_key_dict() assert (len(m) == 0), 'expected len(m) == 0' - all_keys = list() + all_keys: list[tuple[Any, ...]] = list() m['aa', 12, 32, 'mmm'] = 123 # create a value with multiple keys.. assert (len(m) == 1), 'expected len(m) == 1' @@ -432,8 +432,8 @@ def test_multi_key_dict() -> None: 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(',')])) + raw_keys, val = k.strip('{}() ').replace(')', '').split(':') + keys = tuple(sorted([raw_key.strip() for raw_key in raw_keys.split(',')])) sorted_keys_and_values.append((keys, val)) return sorted_keys_and_values @@ -455,10 +455,14 @@ def test_multi_key_dict() -> None: # now check if we can get all possible keys (formed in a list of tuples) # each tuple containing all keys) - res = sorted([sorted([str(x) for x in k]) for k in m.keys()]) - expected = sorted([sorted([str(x) for x in k]) for k in all_keys]) - assert (res == expected), ( - 'unexpected values from m.keys(), got:\n%s\n expected:\n%s' % (res, expected) + res_all_keys: list[list[str] + ] = sorted([sorted([str(x) for x in k]) for k in m.keys()]) + expected_all_keys: list[list[str] + ] = sorted([sorted([str(x) for x in k]) for k in all_keys]) + assert (res_all_keys == expected_all_keys), ( + 'unexpected values from m.keys(), got:\n%s\n expected:\n%s' % ( + res_all_keys, expected_all_keys + ) ) # check default items (which will unpack tupe with key(s) and value) @@ -496,20 +500,23 @@ def test_multi_key_dict() -> None: ) # test values for different types of keys() - expected = set([0, '4']) - res = set(m.values(int)) - assert (res == expected - ), ('m.values(int) are {0}, but expected: {1}.'.format(res, expected)) + expected_int: set[Any] = set([0, '4']) + res_int = set(m.values(int)) + assert (res_int == expected_int), ( + 'm.values(int) are {0}, but expected: {1}.'.format(res_int, expected_int) + ) - expected = sorted(['4', 'abcd']) - res = sorted(m.values(str)) - assert (res == expected - ), ('m.values(str) are {0}, but expected: {1}.'.format(res, expected)) + expected_str = sorted(['4', 'abcd']) + res_str = sorted(m.values(str)) + assert (res_str == expected_str), ( + 'm.values(str) are {0}, but expected: {1}.'.format(res_str, expected_str) + ) - current_values = set([0, '4', 'abcd']) # default (should give all values) - res = set(m.values()) - assert (res == current_values - ), ('m.values() are {0}, but expected: {1}.'.format(res, current_values)) + current_values: set[Any] = set([0, '4', 'abcd']) # default (should give all values) + res_all = set(m.values()) + assert (res_all == current_values), ( + 'm.values() are {0}, but expected: {1}.'.format(res_all, current_values) + ) #test itervalues() (default) - should return all values. (Itervalues for other types # are tested below) @@ -530,36 +537,39 @@ def test_multi_key_dict() -> None: ) # test items(str) - items_for_str = set([(('aa', 'mmm'), '4'), (('something else', ), 'abcd')]) - res = set(m.items(str)) - assert (set(res) == items_for_str), ( - 'items(str): expected {0}, but collected {1}'.format(items_for_str, res) + items_for_str: set[tuple[tuple[str, ...], str] + ] = set([(('aa', 'mmm'), '4'), (('something else', ), 'abcd')]) + res_str_items = set(m.items(str)) + assert (set(res_str_items) == items_for_str), ( + 'items(str): expected {0}, but collected {1}'.format( + items_for_str, res_str_items + ) ) # test items() (default - all items) # we tested keys(), values(), and __get_item__ above so here we'll re-create # all_items using that - all_items = set() - keys = m.keys() + all_items_set: set[tuple[tuple[Any, ...], Any]] = set() + keys_list = m.keys() m.values() - for k in keys: - all_items.add((tuple(k), m[k[0]])) + for k in keys_list: + all_items_set.add((tuple(k), m[k[0]])) - res = set(m.items()) - assert (all_items == res), ( + res_all_items = set(m.items()) + assert (all_items_set == res_all_items), ( 'items() (all items): expected {0},\n\t\t\t\tbut ' - 'collected {1}'.format(all_items, res) + 'collected {1}'.format(all_items_set, res_all_items) ) # now test deletion.. curr_len = len(m) - del m[12] + del m[12] # type: ignore[no-untyped-call] assert (len(m) == curr_len - 1), 'expected len(m) == %d' % (curr_len - 1) assert (not m.has_key(12)), 'expected deleted key to no longer be found!' # try again try: - del m['aa'] + del m['aa'] # type: ignore[no-untyped-call] assert (False), 'cant remove again: item m[\'aa\'] should not exist!' except KeyError: pass @@ -665,8 +675,9 @@ def test_multi_key_dict() -> None: #test keys.. res = [x for x in d.keys()][0] - expected = n, - assert (expected == res), 'Expected \"{0}\", but got: \"{1}\"'.format(expected, res) + expected_key = n, + assert (expected_key == res + ), ('Expected \"{0}\", but got: \"{1}\"'.format(expected_key, res)) res = [x for x in d.keys(datetime.datetime)][0] assert (n == res), 'Expected {0} as a key, but got: {1}'.format(n, res)