Skip to content

Commit

Permalink
chore: fix linting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
FelixTheC committed Oct 6, 2023
1 parent a734b1e commit 2d1f84a
Show file tree
Hide file tree
Showing 13 changed files with 43 additions and 38 deletions.
1 change: 0 additions & 1 deletion easy_property/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@


def action(f, frefs):

"""
This code is original from Ruud van der Ham https://github.com/salabim/easy_property
"""
Expand Down
5 changes: 2 additions & 3 deletions strongtyping/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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__
Expand Down
15 changes: 12 additions & 3 deletions strongtyping/docs_from_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand All @@ -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]}]"
Expand Down Expand Up @@ -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}"
Expand Down
13 changes: 8 additions & 5 deletions strongtyping/docstring_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -226,7 +230,6 @@ def match_class_docstring(
**kwargs,
):
def wrapper(cls):

severity_level = _severity_level(severity)

def inner(*args, **kwargs):
Expand Down
3 changes: 1 addition & 2 deletions strongtyping/easy_property/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand Down
1 change: 0 additions & 1 deletion strongtyping/mypy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
9 changes: 5 additions & 4 deletions strongtyping/strong_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 7 additions & 6 deletions strongtyping/strong_typing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"]))
Expand Down Expand Up @@ -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, )
Expand All @@ -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')
Expand Down
10 changes: 4 additions & 6 deletions strongtyping/tests/test_typed_namedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}],
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions strongtyping/tests/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1040,7 +1039,6 @@ def a(self, val: int):


def test_with_env_severity(monkeypatch):

monkeypatch.setenv("ST_SEVERITY", "disable")

@match_class_typing
Expand Down
2 changes: 1 addition & 1 deletion strongtyping/tests/test_validator_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
1 change: 0 additions & 1 deletion strongtyping/tests/test_with_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
4 changes: 2 additions & 2 deletions strongtyping/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down

0 comments on commit 2d1f84a

Please sign in to comment.