From 2d1f84af4182e5a1c5fcd34db20de4c685297982 Mon Sep 17 00:00:00 2001 From: felix Date: Fri, 6 Oct 2023 21:03:28 +0200 Subject: [PATCH] chore: fix linting issues --- easy_property/__init__.py | 1 - strongtyping/_utils.py | 5 ++--- strongtyping/docs_from_typing.py | 15 ++++++++++++--- strongtyping/docstring_typing.py | 13 ++++++++----- strongtyping/easy_property/__init__.py | 3 +-- strongtyping/mypy.py | 1 - strongtyping/strong_typing.py | 9 +++++---- strongtyping/strong_typing_utils.py | 13 +++++++------ strongtyping/tests/test_typed_namedtuple.py | 10 ++++------ strongtyping/tests/test_typing.py | 4 +--- strongtyping/tests/test_validator_type.py | 2 +- strongtyping/tests/test_with_cache.py | 1 - strongtyping/types.py | 4 ++-- 13 files changed, 43 insertions(+), 38 deletions(-) diff --git a/easy_property/__init__.py b/easy_property/__init__.py index c1e0fb7..e41ef39 100644 --- a/easy_property/__init__.py +++ b/easy_property/__init__.py @@ -10,7 +10,6 @@ def action(f, frefs): - """ This code is original from Ruud van der Ham https://github.com/salabim/easy_property """ diff --git a/strongtyping/_utils.py b/strongtyping/_utils.py index da340a8..ab3c473 100644 --- a/strongtyping/_utils.py +++ b/strongtyping/_utils.py @@ -4,11 +4,10 @@ @created: 20.07.20 @author: felix """ -import inspect import logging import os from types import MethodType -from typing import Any, Type, Union +from typing import Type, Union from strongtyping.config import SEVERITY_LEVEL @@ -109,7 +108,7 @@ def action(f, frefs, type_function): # type: ignore """ if f.__qualname__ == action.qualname: if any(action.f[fref] is not None for fref in frefs.split("_")): - raise AttributeError(f"decorator defined twice") + raise AttributeError("decorator defined twice") else: action.f.update({}.fromkeys(action.f, None)) # reset all values to None action.qualname = f.__qualname__ diff --git a/strongtyping/docs_from_typing.py b/strongtyping/docs_from_typing.py index 62a3a12..d4ab453 100644 --- a/strongtyping/docs_from_typing.py +++ b/strongtyping/docs_from_typing.py @@ -92,7 +92,10 @@ def get_type_info(val, type_origins): return union_types(val, type_origins) elif origins[1].lower() == "dict": try: - return f"{get_origins(val)[1]}({get_type_info(val, type_origins[0])}, {get_type_info(val, type_origins[1])})" + return ( + f"{get_origins(val)[1]}({get_type_info(val, type_origins[0])}, " + f"{get_type_info(val, type_origins[1])})" + ) except TypeError: text = ", ".join( [ @@ -116,7 +119,10 @@ def get_type_info(val, type_origins): fields = { key: get_type_info(key, val) for key, val in val_origins[0].__annotations__.items() } - return f"{val.__name__}[TypedDict]{required} fields are \n\t`{pprint.pformat(fields, sort_dicts=False)}`" + return ( + f"{val.__name__}[TypedDict]{required} " + f"fields are \n\t`{pprint.pformat(fields, sort_dicts=False)}`" + ) elif "Validator" in origins[1]: required_type, *not_needed = type_origins.__args__ text = f"{get_type_info(val, required_type)}[{origins[1]}]" @@ -167,7 +173,10 @@ def docs_from_typing_numpy_format( predefined_info = "\n\t".join(additional_infos.get(f"${idx}", "").split("\n")) predefined_info = f"\n\t{predefined_info}" if predefined_info else "" - info_str = f"{key} : {ARGUMENT_TYPE[func_params[key].kind]} of type {get_type_info(val, type_origins)}" + info_str = ( + f"{key} : {ARGUMENT_TYPE[func_params[key].kind]} " + f"of type {get_type_info(val, type_origins)}" + ) if func_params[key].default is not inspect._empty: info_str = f"{info_str}\n\tDefault is {func_params[key].default}" diff --git a/strongtyping/docstring_typing.py b/strongtyping/docstring_typing.py index aebe7cb..905dc2f 100644 --- a/strongtyping/docstring_typing.py +++ b/strongtyping/docstring_typing.py @@ -172,11 +172,11 @@ def wrapper(func): @functools.wraps(func) def inner(*args, **kwargs): if severity_level > 0: - args = remove_subclass(args, subclass) if cached_set is not None: - # check if func with args and kwargs was checked once before with positive result + # check if func with args and kwargs was + # checked once before with positive result cached_key = (func, args.__str__(), kwargs.__str__()) if cached_key in cached_set: return func(*args, **kwargs) @@ -185,7 +185,8 @@ def inner(*args, **kwargs): docstring_types["self"] = args[0].__class__.__name__ if "cls" in docstring_types: docstring_types["cls"] = args[0].__name__ - # Thanks to Ruud van der Ham who find a better and more stable solution for check_args + # Thanks to Ruud van der Ham who find a better + # and more stable solution for check_args failed_params = tuple( arg_name for arg, arg_name in zip(args, docstring_types) @@ -197,7 +198,10 @@ def inner(*args, **kwargs): if not check_doc_str_type(kwarg, docstring_types.get(kwarg_name)) ) if failed_params: - msg = f'Incorrect parameters: {", ".join(f"{name}: {docstring_types[name]}" for name in failed_params)}' + msg = ( + f"Incorrect parameters: " + f'{", ".join(f"{name}: {docstring_types[name]}" for name in failed_params)}' + ) if excep_raise is not None and severity_level == 1: raise excep_raise(msg) else: @@ -226,7 +230,6 @@ def match_class_docstring( **kwargs, ): def wrapper(cls): - severity_level = _severity_level(severity) def inner(*args, **kwargs): diff --git a/strongtyping/easy_property/__init__.py b/strongtyping/easy_property/__init__.py index 1f73cf0..3b52e1c 100644 --- a/strongtyping/easy_property/__init__.py +++ b/strongtyping/easy_property/__init__.py @@ -10,13 +10,12 @@ def action(f, frefs): - """ This code is original from Ruud van der Ham https://github.com/salabim/easy_property """ if f.__qualname__ == action.qualname: if any(action.f[fref] is not None for fref in frefs.split("_")): - raise AttributeError(f"decorator defined twice") + raise AttributeError("decorator defined twice") else: action.f.update({}.fromkeys(action.f, None)) # reset all values to None action.qualname = f.__qualname__ diff --git a/strongtyping/mypy.py b/strongtyping/mypy.py index d708dcf..226a374 100644 --- a/strongtyping/mypy.py +++ b/strongtyping/mypy.py @@ -6,7 +6,6 @@ from mypy.nodes import FuncBase, SymbolNode from mypy.options import Options from mypy.plugin import AnalyzeTypeContext, Plugin -from mypy.semanal import set_callable_name # type: ignore from mypy.types import Type, TypeVar T = TypeVar("T") diff --git a/strongtyping/strong_typing.py b/strongtyping/strong_typing.py index 52a0347..3282405 100644 --- a/strongtyping/strong_typing.py +++ b/strongtyping/strong_typing.py @@ -42,15 +42,16 @@ def wrapper(func): @wraps(func) def inner(*args, **kwargs): if arg_names and severity_level > SEVERITY_LEVEL.DISABLED.value: - args = remove_subclass(args, subclass) if cached_set is not None and func.__name__ not in IGNORE_FUNCS: - # check if func with args and kwargs was checked once before with positive result + # check if func with args and kwargs was checked + # once before with positive result cached_key = (func, args.__str__(), kwargs.__str__()) if cached_key in cached_set: return func(*args, **kwargs) - # Thanks to Ruud van der Ham who find a better and more stable solution for check_args + # Thanks to Ruud van der Ham who find a better + # and more stable solution for check_args failed_params = tuple( arg_name for arg, arg_name in zip(args, arg_names) @@ -204,7 +205,7 @@ def inner(*args, **cls_kwargs): if cls is not None: if sys.version_info.major >= 3 and sys.version_info.minor > 7: - from typing import Type, _TypedDictMeta + from typing import _TypedDictMeta if isinstance(cls, _TypedDictMeta): return MatchTypedDict(cls) diff --git a/strongtyping/strong_typing_utils.py b/strongtyping/strong_typing_utils.py index 2da9b05..2add5bb 100644 --- a/strongtyping/strong_typing_utils.py +++ b/strongtyping/strong_typing_utils.py @@ -4,7 +4,7 @@ import typing from functools import lru_cache, partial from queue import Queue -from typing import Any, TypeVar, _GenericAlias, _SpecialForm, _type_repr # type: ignore +from typing import Any, TypeVar # type: ignore from strongtyping._utils import ORIGINAL_DUCK_TYPES, install_st_m @@ -15,7 +15,7 @@ from strongtyping_modules.strongtyping_modules import list_elements # type: ignore from strongtyping_modules.strongtyping_modules import set_elements # type: ignore from strongtyping_modules.strongtyping_modules import tuple_elements # type: ignore -except ImportError as e: +except ImportError: extension_module: bool = False else: extension_module = bool(int(os.environ["ST_MODULES_INSTALLED"])) @@ -51,7 +51,8 @@ def __init__(self, message: str): @lru_cache(maxsize=1024) def get_possible_types(typ_to_check, origin_name: str = "") -> typing.Union[tuple, None]: """ - :param typ_to_check: some typing like List[str], Dict[str, int], Tuple[Union[str, int], List[int]] + :param typ_to_check: + some typing like List[str], Dict[str, int], Tuple[Union[str, int], List[int]] :param origin_name: the name of the origin :return: the inner types, classes of the type - List[str] = (str, ) @@ -75,10 +76,10 @@ def get_possible_types(typ_to_check, origin_name: str = "") -> typing.Union[tupl def get_origins(typ_to_check: Any) -> tuple: - from strongtyping.strong_typing import match_class_typing - """ - :param typ_to_check: typ_to_check: some typing like List[str], Dict[str, int], Tuple[Union[str, int], List[int]] + :param typ_to_check: + typ_to_check: some typing like + List[str], Dict[str, int], Tuple[Union[str, int], List[int]] :return: the class, alias_class and the class name - List[str] = (list, 'List') - Dict[str, int] = (dict, 'Dict') diff --git a/strongtyping/tests/test_typed_namedtuple.py b/strongtyping/tests/test_typed_namedtuple.py index f9a4b81..591b340 100644 --- a/strongtyping/tests/test_typed_namedtuple.py +++ b/strongtyping/tests/test_typed_namedtuple.py @@ -214,19 +214,17 @@ def test_typed_namedtuple_instantiate_with_incorrect_types_raises_type_error(dum @pytest.mark.skipif(sys.version_info.minor < 8, reason=SKIP_MESSAGE) def test_typed_namedtuple_incorrect_default_types_raises_type_error(): with pytest.raises(TypeError): - Dummy = typed_namedtuple( - "Dummy", ["spell:str", "mana:int", "effect:list"], defaults=[0, "", ""] - ) + typed_namedtuple("Dummy", ["spell:str", "mana:int", "effect:list"], defaults=[0, "", ""]) with pytest.raises(TypeError): - Dummy = typed_namedtuple( + typed_namedtuple( "Dummy", ["spell:str", "mana:int or str", "effect:list"], defaults=["", (), []], ) with pytest.raises(TypeError): - Dummy = typed_namedtuple( + typed_namedtuple( "Dummy", ["spell:str", "mana:int or str", "effect:list or tuple"], defaults=["", "5", {1, 2}], @@ -285,7 +283,7 @@ def test_typed_namedtuple_rename(): @pytest.mark.skipif(sys.version_info.minor < 8, reason=SKIP_MESSAGE) def test_typed_namedtuple_mixing_typ_and_no_type_not_allowed(): with pytest.raises(TypeError): - Dummy = typed_namedtuple("Dummy", ["spell:str", "mana", "effect:list or tuple"]) + typed_namedtuple("Dummy", ["spell:str", "mana", "effect:list or tuple"]) @pytest.mark.skipif(sys.version_info.minor < 8, reason=SKIP_MESSAGE) diff --git a/strongtyping/tests/test_typing.py b/strongtyping/tests/test_typing.py index 8f890e1..7ca59b0 100644 --- a/strongtyping/tests/test_typing.py +++ b/strongtyping/tests/test_typing.py @@ -245,7 +245,7 @@ def func_a(a: MyType): assert func_a(a=("Lumos", [1, 2, 3], A())) -def test_func_with_own_union_type(): +def test_func_with_own_union_type_2(): class A: pass @@ -772,7 +772,6 @@ def func_a(a: json, b: ujson): @pytest.mark.skip() def test_with_new_type(): - FruitType = NewType("FruitType", Tuple[str, str]) @match_typing @@ -1040,7 +1039,6 @@ def a(self, val: int): def test_with_env_severity(monkeypatch): - monkeypatch.setenv("ST_SEVERITY", "disable") @match_class_typing diff --git a/strongtyping/tests/test_validator_type.py b/strongtyping/tests/test_validator_type.py index 75341c2..d96eaec 100644 --- a/strongtyping/tests/test_validator_type.py +++ b/strongtyping/tests/test_validator_type.py @@ -223,7 +223,7 @@ def foo( foo({2: [2, 4]}) with pytest.raises(TypeError): - AllowedCluster = Validator[Iterable[Union[int, fractions.Fraction, decimal.Decimal]]] + Validator[Iterable[Union[int, fractions.Fraction, decimal.Decimal]]] @pytest.mark.skipif(sys.version_info.minor < 9, reason="Available since 3.9") diff --git a/strongtyping/tests/test_with_cache.py b/strongtyping/tests/test_with_cache.py index 0e71c5f..80dee31 100644 --- a/strongtyping/tests/test_with_cache.py +++ b/strongtyping/tests/test_with_cache.py @@ -80,7 +80,6 @@ def foo(self, val_a: List[int], val_b: Optional[int] = 10): def test_cache_enabled_will_boost(): - assert timeit.timeit("foo(data_1)", globals=globals(), number=1000) > timeit.timeit( "foo_cached(data_1)", globals=globals(), number=1000 ) diff --git a/strongtyping/types.py b/strongtyping/types.py index 87b41d5..d88e232 100644 --- a/strongtyping/types.py +++ b/strongtyping/types.py @@ -90,7 +90,7 @@ def IterValidator(self, parameters, *args, **kwargs): return _IterValidator(self, parameters) else: - from typing import KT, VT, _alias, _GenericAlias, _type_repr # type: ignore + from typing import KT, VT, _alias, _GenericAlias # type: ignore Validator = _alias(_Validator, (KT, VT), inst=False) IterValidator = _alias(_IterValidator, (KT, VT), inst=False) @@ -112,7 +112,7 @@ def __set__(self, instance=None, value=None): required_type, stored_value = self.weakref.get( instance, (self.required_type, self.stored_value) ) - new_required_type, original_type = value[1], required_type + new_required_type, _ = value[1], required_type try: updated_stored_value = new_required_type(stored_value) except TypeError: