diff --git a/src/python/jw/util/ArgsContainer.py b/src/python/jw/util/ArgsContainer.py index aa5f94b..e6a8732 100644 --- a/src/python/jw/util/ArgsContainer.py +++ b/src/python/jw/util/ArgsContainer.py @@ -1,5 +1,5 @@ import argparse -from typing import Iterable, override +from typing import Any, Iterable, override from collections import OrderedDict @@ -23,7 +23,7 @@ class ArgsContainer: # export raise Exception(f'No argument "{name}" defined') @override - def __setattr__(self, name, value): + def __setattr__(self, name: str, value: str) -> None: if name not in self.__kwargs.keys(): raise Exception(f'No argument "{name}" defined') self.__values[name] = value @@ -46,13 +46,13 @@ class ArgsContainer: # export def keys(self) -> Iterable[str]: return self.__args.keys() - def args(self, name) -> str: + def args(self, name: str) -> str: return self.__args[name] - def kwargs(self, name) -> dict[str, str]: + def kwargs(self, name: str) -> dict[str, str]: return self.__kwargs[name] - def dump(self, prio, *args, **kwargs): + def dump(self, prio: int, *args: Any, **kwargs: Any) -> None: caller = get_caller_pos(**kwargs) for name in self.__kwargs.keys(): val = None @@ -63,12 +63,12 @@ class ArgsContainer: # export slog(prio, f'{name}: {val}', caller = caller) @property - def specified_args(self): + def specified_args(self) -> list[str]: return self.__specified_args def add_argument( # export - p: argparse.ArgumentParser | ArgsContainer, name: str, *args, **kwargs -): + p: argparse.ArgumentParser | ArgsContainer, name: str, *args: Any, **kwargs: Any +) -> None: key = name.strip('--').replace('-', '_') if isinstance(p, ArgsContainer): diff --git a/src/python/jw/util/Config.py b/src/python/jw/util/Config.py index bebed1e..83e3317 100644 --- a/src/python/jw/util/Config.py +++ b/src/python/jw/util/Config.py @@ -8,7 +8,7 @@ import sys from collections.abc import Iterator, Mapping from pathlib import Path -from typing import override +from typing import Any, override from .stree import serdes from .log import DEBUG, ERR, slog, get_caller_pos @@ -193,7 +193,7 @@ class Config(Mapping[str, str]): # export return Config(tree = tree, parent = self) return None - def dump(self, prio: int, *args, **kwargs) -> None: + def dump(self, prio: int, *args: Any, **kwargs: Any) -> None: caller = get_caller_pos(1, kwargs) self.__conf.dump(prio, caller = caller, *args, **kwargs) diff --git a/src/python/jw/util/algo/ShuntingYard.py b/src/python/jw/util/algo/ShuntingYard.py index 1c01dc3..46053d0 100644 --- a/src/python/jw/util/algo/ShuntingYard.py +++ b/src/python/jw/util/algo/ShuntingYard.py @@ -10,7 +10,9 @@ 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): + def __init__( + self, func: Any = None, nargs: int = 2, precedence: int = 3, assoc: Any = L + ): self.func: Any | None = func self.nargs = nargs self.prec = precedence @@ -76,7 +78,7 @@ class ShuntingYard(object): # export return r[2:] return r - def tokenize(self, spec) -> list[tuple[str, Any]]: + def tokenize(self, spec: str) -> list[tuple[str, Any]]: regex = "" for k in self.__ops.keys(): @@ -107,7 +109,7 @@ class ShuntingYard(object): # export ) -> None: self.__ops[name] = Operator(func, nargs, precedence, assoc) - def infix_to_postfix(self, infix) -> list[str]: + def infix_to_postfix(self, infix: str) -> list[str]: tokenized = self.tokenize(infix) self.debug("tokenized = ", tokenized) outq: list[str] = [] @@ -237,7 +239,7 @@ class ShuntingYard(object): # export return r #return " ".join(r) - def eval_postfix(self, postfixexpr) -> Any: + def eval_postfix(self, postfixexpr: list[str]) -> Any: self.debug("postfix = ", postfixexpr) vals = Stack() @@ -265,9 +267,7 @@ class ShuntingYard(object): # export return vals.pop() - def eval(self, infix) -> Any: - if not isinstance(infix, str): - return infix + def eval(self, infix: str) -> Any: postfix = self.infix_to_postfix(infix) self.debug(f'"{infix}" --> {postfix}') for token in postfix: @@ -341,7 +341,7 @@ if __name__ == '__main__': return "True" return "False" - def __init__(self, obj) -> None: + def __init__(self, obj: Any) -> 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 a4916f7..0d2f2c5 100644 --- a/src/python/jw/util/asyncio/ShellCmd.py +++ b/src/python/jw/util/asyncio/ShellCmd.py @@ -36,7 +36,9 @@ class ShellCmd: # export Completed = 3 Unnecessary = 4 - def __init__(self, cmdline: list[str], eloop = None, name = None) -> None: + def __init__( + self, cmdline: list[str], eloop: Any = None, name: str | None = None + ) -> None: if eloop is None: eloop = asyncio.get_running_loop() self.__eloop = eloop diff --git a/src/python/jw/util/auth/Auth.py b/src/python/jw/util/auth/Auth.py index d66dc15..68c205c 100644 --- a/src/python/jw/util/auth/Auth.py +++ b/src/python/jw/util/auth/Auth.py @@ -88,10 +88,10 @@ class Auth(abc.ABC): # export base_type: type | None = None, tp: str | None = None, class_name_filter: str | None = None, - module_path = ['jwutils.auth.{type}.Auth'], - module_extra_path = [], - *args, - **kwargs, + module_path: list[str] = ['jwutils.auth.{type}.Auth'], + module_extra_path: list[str] = [], + *args: Any, + **kwargs: Any, ) -> Self: # == Prepare arguments @@ -131,13 +131,13 @@ class Auth(abc.ABC): # export load_object(path, base_type, class_name_filter, conf, *args, **kwargs) ) - def __init__(self, conf: Config, *args, **kwargs) -> None: + def __init__(self, conf: Config, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.__conf = conf self.__base_entity_by_email: dict[str, Entity] | None = None @property - def conf(self): + def conf(self) -> Config: return self.__conf @abc.abstractmethod @@ -163,7 +163,7 @@ class Auth(abc.ABC): # export return self._current_entity() @abc.abstractmethod - def _entity(self, name, kind: Kind) -> Entity: + def _entity(self, name: str, kind: Kind) -> Entity: ... def entity(self, name: str, kind: Kind) -> Entity: @@ -193,7 +193,7 @@ class Auth(abc.ABC): # export # -- Convenience / legacy wrappers - def projects(self, name, flags: ProjectFlags) -> Sequence[str]: + def projects(self, name: str, flags: ProjectFlags) -> Sequence[str]: log( WARNING, 'Using Auth.projects() is deprecated. Use Entity.projects() instead!' diff --git a/src/python/jw/util/auth/dummy/Auth.py b/src/python/jw/util/auth/dummy/Auth.py index b92882c..2dd43d3 100644 --- a/src/python/jw/util/auth/dummy/Auth.py +++ b/src/python/jw/util/auth/dummy/Auth.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, override +from typing import Any, TYPE_CHECKING, override from ...Config import Config from ...log import WARNING, slog @@ -23,8 +23,8 @@ class Entity(EntityBase): # export name: str, conf: Config, kind: Kind, - **kwargs, - ): + **kwargs: Any, + ) -> None: super().__init__(**kwargs) self.__name = name self.__conf = conf @@ -74,7 +74,7 @@ class Entity(EntityBase): # export class Auth(AuthBase): # export - def __init__(self, conf: Config, **kwargs): + def __init__(self, conf: Config, **kwargs: Any) -> None: super().__init__(conf, **kwargs) self.___users: dict[str, EntityBase] | None = None self.__groups = None diff --git a/src/python/jw/util/auth/ldap/Auth.py b/src/python/jw/util/auth/ldap/Auth.py index e6814d3..0ee3bb2 100644 --- a/src/python/jw/util/auth/ldap/Auth.py +++ b/src/python/jw/util/auth/ldap/Auth.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, override +from typing import TYPE_CHECKING, Any, override import ldap # type: ignore[import-untyped] @@ -28,8 +28,8 @@ class Entity(EntityBase): cn: str, email: str, kind: Kind, - **kwargs, - ): + **kwargs: Any, + ) -> None: super().__init__(**kwargs) self.__auth = auth self.__name = name @@ -71,7 +71,7 @@ class Entity(EntityBase): class Auth(AuthBase): # export - def __init__(self, conf: Config, *args, **kwargs): + def __init__(self, conf: Config, *args: Any, **kwargs: Any) -> None: super().__init__(conf, *args, **kwargs) self.___users: dict[str, EntityBase] | None = None self.___user_by_email: dict[str, EntityBase] | None = None @@ -143,8 +143,8 @@ class Auth(AuthBase): # export cn: str, email: str, kind: Kind, - **kwargs, - ): + **kwargs: Any, + ) -> Entity: return Entity( auth = auth, name = name, diff --git a/src/python/jw/util/cast.py b/src/python/jw/util/cast.py index 23795fd..ee5982e 100644 --- a/src/python/jw/util/cast.py +++ b/src/python/jw/util/cast.py @@ -1,3 +1,5 @@ +from typing import Any + import os from collections import OrderedDict @@ -31,7 +33,7 @@ def cast_str_to_int(s_: str) -> int: # export raise Exception(f'Could not convert string "{s}" to int') return int(s) -def cast_str_to_bool(s_: str): # export +def cast_str_to_bool(s_: str) -> bool: # export s = _strip(s_).lower() if s in ['true', 'yes', '1']: return True @@ -45,7 +47,12 @@ _str_cast_functions = OrderedDict( } ) -def guess_type(s: str, default = None, log_level = DEBUG, throw = False): # export +def guess_type( # export + s: str, + default: Any = None, + log_level: int = DEBUG, + throw: bool = False +) -> Any: if s is None: raise Exception('None string passed to guess_type()') for tp, func in _str_cast_functions.items(): @@ -62,12 +69,12 @@ def guess_type(s: str, default = None, log_level = DEBUG, throw = False): # exp def from_str( # export s: str, - target_type = None, - default_type = None, - throw = True, - log_level = WARNING, - caller = None -): + target_type: Any = None, + default_type: Any = None, + throw: bool = True, + log_level: int = WARNING, + caller: Any = None +) -> Any: if target_type is None: for tp, func in _str_cast_functions.items(): try: @@ -90,13 +97,13 @@ def from_str( # export def from_env( # export key: str, - default = None, - target_type = None, - default_type = None, - throw = True, - log_level = WARNING, - caller = None -): + default: Any = None, + target_type: Any = None, + default_type: Any = None, + throw: bool = True, + log_level: int = WARNING, + caller: Any = None +) -> Any: val = os.getenv(key) if val is None: return default @@ -114,12 +121,12 @@ def from_env( # export # deprecated name def cast_str( s: str, - target_type = None, - default_type = None, - throw = True, - log_level = WARNING, - caller = None -): + target_type: Any = None, + default_type: Any = None, + throw: bool = True, + log_level: int = WARNING, + caller: Any = None +) -> Any: return from_str( s, target_type = target_type, diff --git a/src/python/jw/util/db/DataBase.py b/src/python/jw/util/db/DataBase.py index ef174cb..94d4ecd 100644 --- a/src/python/jw/util/db/DataBase.py +++ b/src/python/jw/util/db/DataBase.py @@ -20,10 +20,10 @@ class DataBase(abc.ABC): conf.dump(NOTICE, "Initializing database with configuration") @abc.abstractmethod - def _create_session(self): + def _create_session(self) -> Session: pass - def _delete_session(self, session: Session): + def _delete_session(self, session: Session) -> None: del session @property diff --git a/src/python/jw/util/db/TableIoHandler.py b/src/python/jw/util/db/TableIoHandler.py index e82724a..81070c7 100644 --- a/src/python/jw/util/db/TableIoHandler.py +++ b/src/python/jw/util/db/TableIoHandler.py @@ -37,7 +37,7 @@ class TableIoHandler(ABC): # export buf: list[dict[str, Any]] = [] non_nullable = self._table_meta.not_null_insertible_columns try: - rows_check_not_null(rows, non_nullable, buf = buf) + rows_check_not_null(rows, list(non_nullable), buf = buf) except: cn = self.__class__.__name__ tn = self._table_name @@ -65,15 +65,19 @@ class TableIoHandler(ABC): # export return self._table_meta.log_columns @abstractmethod - def _load(self, uri: str, reference) -> TType: + def _load(self, uri: str, reference: Any) -> TType: pass @abstractmethod - def _store(self, uri: str, data: TType): + def _store(self, uri: str, data: TType) -> None: pass def load( - self, uri: str, reference, check_duplicates = False, write_csv = None + self, + uri: str, + reference: Any, + check_duplicates: bool = False, + write_csv: Any = None ) -> TType: slog(INFO, f'Reading table "{self._table_name}" from "{uri}"') ret = cast('List[Dict[str, Any]]', self._load(uri, reference)) diff --git a/src/python/jw/util/db/query/Queries.py b/src/python/jw/util/db/query/Queries.py index 64c282b..8016362 100644 --- a/src/python/jw/util/db/query/Queries.py +++ b/src/python/jw/util/db/query/Queries.py @@ -25,11 +25,11 @@ class Queries(abc.ABC): # export # -- implement API @override - def _run(self, session, *args, **kwargs) -> QueryResult: + def _run(self, session: Any, *args: Any, **kwargs: Any) -> QueryResult: return cast('QueryResult', self.__func(session, *args, **kwargs)) @override - def _register(self): + def _register(self) -> None: raise Exception('Can\'t call register on this object') @override @@ -37,7 +37,7 @@ class Queries(abc.ABC): # export return self.__query.column_names @property - def name(self): + def name(self) -> str: return self.__name def __init__(self, db: DataBase) -> None: @@ -45,7 +45,7 @@ class Queries(abc.ABC): # export self.__db = db self.__queries: dict[str, Any] = dict() - def __getitem__(self, name) -> Query: + def __getitem__(self, name: str) -> Query: try: return cast('Queries.Query', self.__queries[name]) except Exception as e: @@ -53,14 +53,14 @@ class Queries(abc.ABC): # export slog_m(ERR, '\n'.join(self.__queries.keys())) raise - def keys(self): + def keys(self) -> Any: return self.__queries.keys() @property def db(self) -> DataBase: return self.__db - def load(self, modules: list[str], cls = QueryBase): + def load(self, modules: list[str], cls: Any = QueryBase) -> None: for path in modules: slog(INFO, f'Loading modules from {path}') for c in load_classes(path, cls): @@ -70,7 +70,7 @@ class Queries(abc.ABC): # export def schema(self) -> Schema: return cast('Schema', self.__db.schema) - def add(self, query: QueryBase, query_name: str, location: str, func: Any): + def add(self, query: QueryBase, query_name: str, location: str, func: Any) -> None: slog(INFO, f'Adding query "{query_name}" on location "{location}"') assert (isinstance(query_name, str)) assert (isinstance(location, str)) @@ -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) -> None: + def _add(self, query: Any) -> None: pass diff --git a/src/python/jw/util/db/query/Query.py b/src/python/jw/util/db/query/Query.py index 3ce7c17..dc62f3d 100644 --- a/src/python/jw/util/db/query/Query.py +++ b/src/python/jw/util/db/query/Query.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, cast if TYPE_CHECKING: from ..DataBase import DataBase from ..Session import Session + from .Queries import Queries from .QueryResult import QueryResult class Query(abc.ABC): # export @@ -17,11 +18,11 @@ class Query(abc.ABC): # export # -- pure virtuals @abc.abstractmethod - def _run(self, session: Session, *args, **kwargs) -> QueryResult: + def _run(self, session: Session, *args: Any, **kwargs: Any) -> QueryResult: raise Exception('Called pure virtual _run()') @abc.abstractmethod - def _register(self): + def _register(self) -> None: raise Exception('Called pure virtual _register()') @abc.abstractmethod @@ -30,20 +31,20 @@ class Query(abc.ABC): # export # -- used by Queries class - def register(self): + def register(self) -> None: return self._register() # -- to be used - def _add(self, query_name: str, location: str, func: Any): - return self.__parent.add(self, query_name, location, func) + def _add(self, query_name: str, location: str, func: Any) -> None: + self.__parent.add(self, query_name, location, func) - def run(self, session: Session, *args, **kwargs) -> QueryResult: + def run(self, session: Session, *args: Any, **kwargs: Any) -> QueryResult: return self._run(session, *args, **kwargs) @property - def parent(self): - return self.__parent + def parent(self) -> Queries: + return cast('Queries', self.__parent) @property def db(self) -> DataBase: diff --git a/src/python/jw/util/db/query/QueryResult.py b/src/python/jw/util/db/query/QueryResult.py index bf4b1cb..597104f 100644 --- a/src/python/jw/util/db/query/QueryResult.py +++ b/src/python/jw/util/db/query/QueryResult.py @@ -41,7 +41,7 @@ class QueryResult(abc.ABC): # export def rows(self) -> list[Any]: return self._cast(ResType.Scalars) - def pages(self, per_page = 20, page = 1) -> Any: + def pages(self, per_page: int = 20, page: int = 1) -> Any: return self._cast(ResType.Pages, per_page = per_page, page = page) def one(self) -> Any: @@ -57,5 +57,5 @@ class QueryResult(abc.ABC): # export # -- pure virtuals @abc.abstractmethod - def _cast(self, res_type: ResType, **kwargs) -> Union[Any, list[Any]]: + def _cast(self, res_type: ResType, **kwargs: Any) -> Union[Any, list[Any]]: pass diff --git a/src/python/jw/util/db/rows.py b/src/python/jw/util/db/rows.py index 630f661..0d12733 100644 --- a/src/python/jw/util/db/rows.py +++ b/src/python/jw/util/db/rows.py @@ -19,7 +19,11 @@ 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) -> list[int]: # export +def rows_duplicates( # export + rows: list[dict[str, Any]], + log_prio: int = INFO, + caller: Any = None +) -> list[int]: def __equal(r1: dict[str, Any], r2: dict[str, Any]) -> bool: for col in set(r1.keys()) | set(r2.keys()): @@ -115,12 +119,12 @@ def rows_rewrite_regex(rows, rules): # export def rows_check_not_null( # export rows: list[dict[str, Any]], - keys, - log_prio = WARNING, + keys: str | list[str], + log_prio: int = WARNING, buf: list[dict[str, Any]] | None = None, - stat_key = None, + stat_key: str | None = None, throw: bool = True, - caller = None + caller: Any = None ) -> list[dict[str, Any]]: if isinstance(keys, str): keys = [keys] @@ -157,16 +161,18 @@ def rows_check_not_null( # export return buf def rows_dumps( # export - rows, - log_prio = INFO, - caller = None, - use_cols = None, - skip_cols = None, - table_name = None, - out_path = 'log', - heading = None, - lead = None, - tablefmt = None + rows: list[dict[str, Any]], + log_prio: int = INFO, + caller: Any = None, + use_cols: list[str] | None = None, + skip_cols: list[str] | None = None, + table_name: str | None = None, + out_path: str = 'log', + heading: str | None = None, + lead: str | list[str] | None = None, + separator: str = ' ', + prefix: str = ' | ', + tablefmt: str | None = None ) -> str: headers = 'keys' @@ -253,16 +259,16 @@ def rows_dumps( # export ) def rows_dump( # export - rows, - log_prio = INFO, - caller = None, - use_cols = None, - skip_cols = None, - table_name = None, - out_path = 'log', - heading = None, - lead = None, - tablefmt = None + rows: list[dict[str, Any]], + log_prio: int = INFO, + caller: Any = None, + use_cols: list[str] | None = None, + skip_cols: list[str] | None = None, + table_name: str | None = None, + out_path: str = 'log', + heading: str | None = None, + lead: str | list[str] | None = None, + tablefmt: str | None = None ) -> None: if not prio_gets_logged(log_prio): diff --git a/src/python/jw/util/db/schema/Column.py b/src/python/jw/util/db/schema/Column.py index c0a264c..ecbb31e 100644 --- a/src/python/jw/util/db/schema/Column.py +++ b/src/python/jw/util/db/schema/Column.py @@ -32,7 +32,7 @@ class Column(abc.ABC): # export return f'{self.__table.name}.{self.__name}: {self.__data_type}' @override - def __eq__(self, rhs) -> bool: + def __eq__(self, rhs: Any) -> bool: if isinstance(rhs, Column): if self.__table != rhs.__table: return False @@ -117,7 +117,7 @@ class Column(abc.ABC): # export self.__foreign_keys = fks if fks else None return self.__foreign_keys - def foreign_key(self, table) -> Optional[Any]: + def foreign_key(self, table: Table) -> Optional[Any]: if self.__foreign_keys_by_table is None: self.__foreign_keys_by_table = dict() for col in self.foreign_keys: # type: ignore[union-attr] # Any not iterable diff --git a/src/python/jw/util/db/schema/CompositeForeignKey.py b/src/python/jw/util/db/schema/CompositeForeignKey.py index ee4fc8e..5a93f32 100644 --- a/src/python/jw/util/db/schema/CompositeForeignKey.py +++ b/src/python/jw/util/db/schema/CompositeForeignKey.py @@ -15,7 +15,7 @@ class CompositeForeignKey: # export self, child_col_set: ColumnSet, parent_col_set: ColumnSet ): # TODO: Implement alternative ways to construct - def __table(s) -> 'Table': + def __table(s: Any) -> 'Table': ret: 'Table | None' = None for c in s: if ret is None: @@ -83,7 +83,7 @@ class CompositeForeignKey: # export def parent_columns(self) -> ColumnSet: return self.__parent_col_set - def parent_column(self, child_column) -> Any: + def parent_column(self, child_column: Any) -> Any: child_column if isinstance(child_column, str) else child_column.name if self.__parent_columns_by_child_column is None: d: dict[str, Any] = {} @@ -93,7 +93,7 @@ class CompositeForeignKey: # export self.__parent_columns_by_child_column = d return self.__parent_columns_by_child_column[child_column] - def child_column(self, parent_column) -> Any: + def child_column(self, parent_column: Any) -> Any: slog( WARNING, f'{self}: Looking for child column belonging to parent column ' diff --git a/src/python/jw/util/db/schema/Schema.py b/src/python/jw/util/db/schema/Schema.py index d0a23f1..03c7dd7 100644 --- a/src/python/jw/util/db/schema/Schema.py +++ b/src/python/jw/util/db/schema/Schema.py @@ -46,7 +46,7 @@ class Schema(abc.ABC): # export pass @abc.abstractmethod - def _access_defining_columns(self): + def _access_defining_columns(self) -> list[str]: pass @abc.abstractmethod @@ -77,7 +77,7 @@ class Schema(abc.ABC): # export return self.__tables.values() @property - def access_defining_columns(self): + def access_defining_columns(self) -> list[str]: if self.__access_defining_columns is None: self.__access_defining_columns = self._access_defining_columns() return self.__access_defining_columns @@ -91,7 +91,7 @@ class Schema(abc.ABC): # export def table(self, name: str) -> Table: return self.__tables[name] - def table_by_model_name(self, name: str, throw = False) -> Table: + def table_by_model_name(self, name: str, throw: bool = False) -> Table: for table in self.__tables.values(): if table.model_name == name: return table diff --git a/src/python/jw/util/db/schema/Table.py b/src/python/jw/util/db/schema/Table.py index 27adab7..e78b89a 100644 --- a/src/python/jw/util/db/schema/Table.py +++ b/src/python/jw/util/db/schema/Table.py @@ -4,7 +4,7 @@ import abc import re from collections import OrderedDict -from typing import TYPE_CHECKING, cast, override +from typing import TYPE_CHECKING, Any, Self, cast, override from urllib.parse import quote_plus from ...log import ERR, WARNING, slog, throw @@ -13,14 +13,15 @@ from .Column import Column from .ColumnSet import ColumnSet if TYPE_CHECKING: - from typing import Any, Iterable, Optional, Self, Union + from typing import Iterable, Optional, Union from .CompositeForeignKey import CompositeForeignKey from .DataType import DataType + from .Schema import Schema class Table(abc.ABC): # export - def __init__(self, schema, name: str): + def __init__(self, schema: Schema, name: str): assert (isinstance(name, str)) self.__schema = schema self.__name = name @@ -72,10 +73,10 @@ class Table(abc.ABC): # export @property def __relationship_by_foreign_table(self) -> dict[str, Self]: if self.___relationship_by_foreign_table is None: - ret: dict[str, Self] = dict() + ret: dict[str, Any] = dict() for member_name, table_name in self.relationships: - ret[member_name] = self.schema[table_name] - self.___relationship_by_foreign_table = ret + ret[member_name] = cast('Self', self.schema[table_name]) + self.___relationship_by_foreign_table = cast('dict[str, Self]', ret) return self.___relationship_by_foreign_table @property @@ -105,7 +106,7 @@ class Table(abc.ABC): # export return self.__columns[index] @override - def __eq__(self, rhs) -> bool: + def __eq__(self, rhs: Any) -> bool: if isinstance(rhs, Table): if self.__name != rhs.__name: return False @@ -128,7 +129,7 @@ class Table(abc.ABC): # export pass @abc.abstractmethod - def _column_data_type(self, name) -> DataType: + def _column_data_type(self, name: str) -> DataType: pass @abc.abstractmethod @@ -164,7 +165,7 @@ class Table(abc.ABC): # export pass @abc.abstractmethod - def _column_default(self, name) -> Any: + def _column_default(self, name: str) -> Any: pass @abc.abstractmethod @@ -233,7 +234,7 @@ class Table(abc.ABC): # export # -- To be used - def column_default(self, name) -> Any: + def column_default(self, name: str) -> Any: if self.__column_default is None: ret: dict[str, Any] = dict() for name in self.column_names: @@ -323,7 +324,7 @@ class Table(abc.ABC): # export self.__add_row_location_rule = self._add_row_location_rule() return self.__add_row_location_rule - def add_row_location(self, *args, **kwargs) -> Optional[str]: + def add_row_location(self, *args: Any, **kwargs: Any) -> Optional[str]: ret = str(self.add_row_location_rule) for col in self.primary_keys: if col in kwargs: # FIXME: Poor man's row location assembly @@ -341,10 +342,10 @@ class Table(abc.ABC): # export return self.__add_child_row_location_rules.get(child_table) def add_child_row_location(self, parent_table: Union[Self, str], - **kwargs) -> Optional[str]: + **kwargs: Any) -> Optional[str]: ret = self.add_child_row_location_rule(parent_table) if isinstance(parent_table, str): - parent_table = self.schema[parent_table] + parent_table = cast('Self', self.schema[parent_table]) if ret is None: return None for cfk in self.foreign_keys_to_parent_table(parent_table): @@ -460,8 +461,9 @@ class Table(abc.ABC): # export def foreign_key_parent_tables(self): return self.__foreign_key_parent_tables.values() - def foreign_keys_to_parent_table(self, - parent_table) -> Iterable[CompositeForeignKey]: + def foreign_keys_to_parent_table( + self, parent_table: Any + ) -> Iterable[CompositeForeignKey]: if self.__foreign_keys_to_parent_table is None: self.__foreign_keys_to_parent_table = OrderedDict() for cfk in self.foreign_key_constraints: diff --git a/src/python/jw/util/db/schema/utils.py b/src/python/jw/util/db/schema/utils.py index 43f137b..e1960d8 100644 --- a/src/python/jw/util/db/schema/utils.py +++ b/src/python/jw/util/db/schema/utils.py @@ -7,7 +7,7 @@ from ...log import NOTICE, slog if TYPE_CHECKING: from .Schema import Schema -def check_schema(schema: Schema): # export +def check_schema(schema: Schema) -> None: # export slog(NOTICE, f'There are {len(schema)} tables in the database') for cfk in schema.foreign_key_constraints: for fk in cfk: diff --git a/src/python/jw/util/graph/yed/MapAttr2Shape.py b/src/python/jw/util/graph/yed/MapAttr2Shape.py index 455b660..40f0970 100644 --- a/src/python/jw/util/graph/yed/MapAttr2Shape.py +++ b/src/python/jw/util/graph/yed/MapAttr2Shape.py @@ -35,12 +35,12 @@ class MapAttr2Shape: # export for name, url in self.__ns.items(): ET.register_namespace(name, url) - def __keys(self, root) -> dict[str, str]: + def __keys(self, root: ET.Element) -> dict[str, str]: ret: dict[str, str] = {} for el in root.findall('key', self.__ns): attr_name = el.get('attr.name') id = el.get('id') - if attr_name is not None: + if attr_name is not None and id is not None: ret[attr_name] = id return ret @@ -50,7 +50,7 @@ class MapAttr2Shape: # export return None return data.text - def __attribs(self, node, keys) -> dict[str, str]: + def __attribs(self, node: ET.Element, keys: dict[str, str]) -> dict[str, str]: ret: dict[str, str] = {} for name, key in keys.items(): val = self.__value(node, key) @@ -70,9 +70,9 @@ class MapAttr2Shape: # export el.set(attr, val) root.append(el) - def __massage_node(self, node, keys: dict[str, str]) -> None: + def __massage_node(self, node: ET.Element, keys: dict[str, str]) -> None: - def __add(parent, d: dict[str, Any]): + def __add(parent: ET.Element, d: dict[str, Any]) -> None: for tag, content in d.items(): if tag.find('y:') != -1: ns, tag = tag.split(':') @@ -204,9 +204,11 @@ class MapAttr2Shape: # export __add(node, shape) - def __massage_nodes(self, root) -> None: + def __massage_nodes(self, root: ET.Element) -> None: keys = self.__keys(root) graph = root.find('graph', self.__ns) + if graph is None: + return for node in graph: self.__massage_node(node, keys) diff --git a/src/python/jw/util/ldap.py b/src/python/jw/util/ldap.py index 14ee82a..5b15426 100644 --- a/src/python/jw/util/ldap.py +++ b/src/python/jw/util/ldap.py @@ -20,19 +20,25 @@ if TYPE_CHECKING: from .Config import Config as BaseConfig class Config: + __ldap_uri: str | None + __bind_dn: str | None + __bind_pw: str | None + __base_dn: str | None - def __init__(self, external: BaseConfig | None = None): + def __init__(self, external: BaseConfig | None = None) -> None: self.__external = external - for attr in ['ldap_uri', 'bind_dn', 'bind_pw', 'base_dn']: - setattr(self, '_Config__' + attr, None) + self.__ldap_uri = None + self.__bind_dn = None + self.__bind_pw = None + self.__base_dn = None - def __get(self, key: str, default: str | None): + def __get(self, key: str, default: str | None) -> str | None: if not self.__external: return default return self.__external.value(key, default = default) @property - def ldap_uri(self): + def ldap_uri(self) -> str | None: if self.__ldap_uri is None: for key in ['ldap_uri', 'uri']: self.__ldap_uri = self.__get(key, default = None) @@ -47,7 +53,7 @@ class Config: self.__ldap_uri = rhs @property - def bind_dn(self): + def bind_dn(self) -> str | None: if self.__bind_dn is None: self.__bind_dn = self.__get( 'bind_dn', @@ -60,11 +66,13 @@ class Config: self.__bind_dn = rhs @property - def bind_pw(self): + def bind_pw(self) -> str | None: if self.__bind_pw is None: + ret: str | None = None for key in ['bind_pw', 'password']: - ret = self.__get(key, default = None) - if ret is not None: + val = self.__get(key, default = None) + if val is not None: + ret = val break if ret is None: ldap_secret_file = self.__get( @@ -83,7 +91,7 @@ class Config: self.__bind_pw = rhs @property - def base_dn(self): + def base_dn(self) -> str | None: if self.__base_dn is None: self.__base_dn = self.__get('base_dn', default = 'dc=jannet,dc=de') return self.__base_dn @@ -98,7 +106,9 @@ class Connection: # export Must = auto() May = auto() - def __init__(self, conf: Config | BaseConfig | None = None, backtrace = False): + def __init__( + self, conf: Config | BaseConfig | None = None, backtrace: bool = False + ): uri: str | None = None c = conf if isinstance(conf, Config) else Config(conf) try: @@ -125,10 +135,10 @@ class Connection: # export self.__object_classes_by_name: dict[str, ObjectClass] | None = None @property - def ldap(self): + def ldap(self) -> Any: return self.__ldap - def add(self, attrs: dict[str, bytes], dn: str | None = None): + def add(self, attrs: dict[str, bytes], dn: str | None = None) -> None: if dn is None: if 'dn' not in attrs: raise Exception('No DN to add an LDAP entry to') @@ -144,9 +154,11 @@ class Connection: # export slog(ERR, f'{dn}: Failed to add entry {attrs} ({e})') raise - def delete(self, dn: str, recursive = False, force_existence: bool = False): + def delete( + self, dn: str, recursive: bool = False, force_existence: bool = False + ) -> None: - def __walk_cb_delete(conn: Connection, entry, context): + def __walk_cb_delete(conn: Connection, entry: Any, context: Any) -> None: self.walk( __walk_cb_delete, base = entry[0], @@ -178,18 +190,18 @@ class Connection: # export self, callback: Callable[[Self, Any, Any], None], base: str, - scope, - context = None, - filterstr = None, - attrlist = None, - attrsonly = 0, - serverctrls = None, - clientctrls = None, - timeout = -1, - sizelimit = 0, + scope: Any, + context: Any = None, + filterstr: Any = None, + attrlist: Any = None, + attrsonly: int = 0, + serverctrls: Any = None, + clientctrls: Any = None, + timeout: int = -1, + sizelimit: int = 0, decode: bool = False, unroll: bool = False - ): + ) -> None: # TODO: Support ignored arguments search_return = self.__ldap.search( @@ -224,19 +236,19 @@ class Connection: # export def find( self, base: str, - scope, - filterstr = None, - attrlist = None, - attrsonly = 0, - serverctrls = None, - clientctrls = None, - timeout = -1, - sizelimit = 0, - assert_unique = False, - assert_not_empty = False, - ): + scope: Any, + filterstr: Any = None, + attrlist: Any = None, + attrsonly: int = 0, + serverctrls: Any = None, + clientctrls: Any = None, + timeout: int = -1, + sizelimit: int = 0, + assert_unique: bool = False, + assert_not_empty: bool = False, + ) -> list[Any]: - def __walk_cb_find(conn: Connection, entry: Any, context: Any): + def __walk_cb_find(conn: Connection, entry: Any, context: Any) -> None: result.append(entry) def __search() -> str: @@ -305,16 +317,18 @@ class Connection: # export ret[name.lower()] = oc return self.__object_classes_by_name - def __oc_recurse_to_top(self, cur: str | ObjectClass, cb, context): + def __oc_recurse_to_top( + self, cur: str | ObjectClass, cb: Any, context: Any + ) -> None: cur_oc = cur if isinstance(cur, ObjectClass) else self.object_class_by_name[ cur.lower()] for s in cur_oc.sup: self.__oc_recurse_to_top(s, cb, context) cb(cur_oc, context) - def object_class_path(self, leaf: str | ObjectClass): + def object_class_path(self, leaf: str | ObjectClass) -> Any: - def cb(oc, context): + def cb(oc: Any, context: Any) -> None: ret.append(oc) ret: list[str] = [] @@ -379,7 +393,7 @@ class Connection: # export cur |= set(oc.may) # pyright: ignore[reportAttributeAccessIssue] if cur: all_attrs |= cur - attrs_by_origin[oc] = cur + attrs_by_origin[str(oc)] = cur return attrs_by_origin if origins else all_attrs def is_derived_class(self, name, base_candidate): diff --git a/src/python/jw/util/misc.py b/src/python/jw/util/misc.py index bc208fa..a5f1f8c 100644 --- a/src/python/jw/util/misc.py +++ b/src/python/jw/util/misc.py @@ -61,7 +61,9 @@ def object_builtin_name(o: object, full: bool = True) -> str: # export return o.__class__.__name__ # Avoid reporting __builtin__ return module + '.' + o.__class__.__name__ -def get_derived_classes(mod, base: type[Any], flt = None) -> list[type[Any]]: # export +def get_derived_classes(mod: Any, + base: type[Any], + flt: Any = None) -> list[type[Any]]: # export members = inspect.getmembers(mod, inspect.isclass) ret: list[type[Any]] = [] for name, c in members: @@ -83,7 +85,7 @@ def get_derived_classes(mod, base: type[Any], flt = None) -> list[type[Any]]: # def load_classes( # export path: str, baseclass: type[Any], - flt = None, + flt: Any = None, ) -> list[type[Any]]: ret: list[type[Any]] = [] for p in path.split(':'): @@ -120,7 +122,7 @@ def load_class_names( # export path: str, baseclass: type[Any], flt: str | None = None, - remove_flt = False + remove_flt: bool = False ) -> list[str]: classes = load_classes(path, baseclass, flt) ret = [] @@ -138,8 +140,8 @@ def load_object( # export module_path: str | Iterable[str], baseclass: type, class_name_filter: str|None = None, - *args, - **kwargs, + *args: Any, + **kwargs: Any, ) -> Any: return load_class( module_path, baseclass, class_name_filter = class_name_filter @@ -158,7 +160,7 @@ def commit_tmpfile(tmp: str, path: str) -> None: # export log.slog(log.NOTICE, "saving {}".format(path), caller = caller) os.rename(path + '.tmp', path) -def multi_regex_edit(spec, strings: Iterable[str]) -> list[str]: # export +def multi_regex_edit(spec: Any, strings: Iterable[str]) -> list[str]: # export strings = list(strings) r: list[str] for cmd in spec: @@ -198,7 +200,7 @@ def is_multi_value(obj: Any) -> bool: # export return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes)) def dump_dict( # export - prio: int, obj: Mapping[str, Any] | None, *args, **kwargs + prio: int, obj: Mapping[str, Any] | None, *args: Any, **kwargs: Any ) -> None: import json caller = log.get_caller_pos(kwargs = kwargs) @@ -221,7 +223,9 @@ def dump_dict( # export log.log(prio, f'| {line}', caller = caller) log.log(prio, f'`{header}', caller = caller) -def dump(prio: int, objects: Iterable[Any], *args, **kwargs) -> None: # export +def dump( # export + prio: int, objects: Iterable[Any], *args: Any, **kwargs: Any +) -> None: caller = log.get_caller_pos(kwargs = kwargs) log.slog(prio, ",---------- {}".format(' '.join(args)), caller = caller) prefix = " | " diff --git a/src/python/jw/util/multi_key_dict.py b/src/python/jw/util/multi_key_dict.py index 4390c65..44c66b4 100644 --- a/src/python/jw/util/multi_key_dict.py +++ b/src/python/jw/util/multi_key_dict.py @@ -260,7 +260,7 @@ class multi_key_dict(object): for value in self.items_dict.values(): yield value - def items(self, key_type: Any = None, return_all_keys: bool = False): + def items(self, key_type: Any = None, return_all_keys: bool = False) -> Any: """ Returns an iterator (Python 3) or list (Python 2) over items.""" if _python3: return self.iteritems(key_type, return_all_keys)