From 7abacca0d12a4147c4e13127cb95cbe21ee8a591 Mon Sep 17 00:00:00 2001 From: Jovial Joe Jayarson Date: Wed, 22 Feb 2023 14:59:53 +0530 Subject: [PATCH] maint: improve type annotations - prefer type inference over explicit typing for function returns - removes unsettling code in comments from `between.py` - uses `local` instead of `project` to refer local imports --- tests/test_between.py | 11 +++++------ validators/_extremes.py | 4 ++-- validators/between.py | 7 ++----- validators/length.py | 2 +- validators/utils.py | 14 +++++++------- 5 files changed, 17 insertions(+), 21 deletions(-) diff --git a/tests/test_between.py b/tests/test_between.py index 962ce23a..d257fe50 100644 --- a/tests/test_between.py +++ b/tests/test_between.py @@ -8,10 +8,9 @@ # external import pytest -# project +# local from validators import between, ValidationFailure - T = TypeVar("T", int, float, str, datetime) @@ -19,7 +18,7 @@ ("value", "min_val", "max_val"), [(12, 11, 13), (12, None, 14), (12, 11, None), (12, 12, 12)], ) -def test_returns_true_on_valid_range(value: T, min_val: T, max_val: T) -> None: +def test_returns_true_on_valid_range(value: T, min_val: T, max_val: T): """Test returns true on valid range.""" assert between(value, min_val=min_val, max_val=max_val) @@ -28,7 +27,7 @@ def test_returns_true_on_valid_range(value: T, min_val: T, max_val: T) -> None: ("value", "min_val", "max_val"), [(12, 13, 12), (12, None, None)], ) -def test_raises_assertion_error_for_invalid_args(value: T, min_val: T, max_val: T) -> None: +def test_raises_assertion_error_for_invalid_args(value: T, min_val: T, max_val: T): """Test raises assertion error for invalid args.""" with pytest.raises(AssertionError): assert between(value, min_val=min_val, max_val=max_val) @@ -43,7 +42,7 @@ def test_raises_assertion_error_for_invalid_args(value: T, min_val: T, max_val: (30, 40, "string"), ], ) -def test_raises_type_error_for_invalid_args(value: T, min_val: T, max_val: T) -> None: +def test_raises_type_error_for_invalid_args(value: T, min_val: T, max_val: T): """Test raises type error for invalid args.""" with pytest.raises(TypeError): assert between(value, min_val=min_val, max_val=max_val) @@ -53,7 +52,7 @@ def test_raises_type_error_for_invalid_args(value: T, min_val: T, max_val: T) -> ("value", "min_val", "max_val"), [(12, 13, 14), (12, None, 11), (12, 13, None)], ) -def test_returns_failed_validation_on_invalid_range(value: T, min_val: T, max_val: T) -> None: +def test_returns_failed_validation_on_invalid_range(value: T, min_val: T, max_val: T): """Test returns failed validation on invalid range.""" result = between(value, min_val=min_val, max_val=max_val) assert isinstance(result, ValidationFailure) diff --git a/validators/_extremes.py b/validators/_extremes.py index 26a522e2..70df87e0 100644 --- a/validators/_extremes.py +++ b/validators/_extremes.py @@ -28,7 +28,7 @@ class AbsMax: .. versionadded:: 0.2 """ - def __ge__(self, other: Any) -> bool: + def __ge__(self, other: Any): """GreaterThanOrEqual.""" return other is not AbsMax @@ -55,6 +55,6 @@ class AbsMin: .. versionadded:: 0.2 """ - def __le__(self, other: Any) -> bool: + def __le__(self, other: Any): """LessThanOrEqual.""" return other is not AbsMin diff --git a/validators/between.py b/validators/between.py index db674e8d..401a9853 100644 --- a/validators/between.py +++ b/validators/between.py @@ -5,7 +5,7 @@ from typing import TypeVar, Union from datetime import datetime -# project +# local from ._extremes import AbsMax, AbsMin from .utils import validator @@ -19,7 +19,7 @@ def between( *, min_val: Union[T, AbsMin, None] = None, max_val: Union[T, AbsMax, None] = None, -) -> bool: +): """Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates @@ -80,9 +80,6 @@ def between( if min_val is None: min_val = AbsMin() - # if isinstance(min_val, AbsMin) and isinstance(max_val, AbsMax): - # return min_val <= value <= max_val - if isinstance(min_val, AbsMin): if type(value) is not type(max_val): raise TypeError("`value` and `max_val` must be of same type") diff --git a/validators/length.py b/validators/length.py index 4c851333..68873ef4 100644 --- a/validators/length.py +++ b/validators/length.py @@ -1,7 +1,7 @@ """Length.""" # -*- coding: utf-8 -*- -# project +# local from .between import between from .utils import validator diff --git a/validators/utils.py b/validators/utils.py index 938e3934..5fd7697d 100644 --- a/validators/utils.py +++ b/validators/utils.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # standard -from typing import Any, Callable, Dict, Literal, Union +from typing import Any, Callable, Dict from inspect import getfullargspec from itertools import chain @@ -15,23 +15,23 @@ def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any]): self.func = function self.__dict__.update(arg_dict) - def __repr__(self) -> str: + def __repr__(self): """Repr Validation Failure.""" return ( f"ValidationFailure(func={self.func.__name__}, " + f"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})" ) - def __str__(self) -> str: + def __str__(self): """Str Validation Failure.""" return repr(self) - def __bool__(self) -> Literal[False]: + def __bool__(self): """Bool Validation Failure.""" return False -def _func_args_as_dict(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Dict[str, Any]: +def _func_args_as_dict(func: Callable[..., Any], *args: Any, **kwargs: Any): """Return function's positional and key value arguments as an ordered dictionary.""" # TODO: find more efficient way to do it return dict( @@ -40,7 +40,7 @@ def _func_args_as_dict(func: Callable[..., Any], *args: Any, **kwargs: Any) -> D ) -def validator(func: Callable[..., Any]) -> Callable[..., Union[Literal[True], ValidationFailure]]: +def validator(func: Callable[..., Any]): """A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value @@ -65,7 +65,7 @@ def validator(func: Callable[..., Any]) -> Callable[..., Union[Literal[True], Va Wrapper function as a decorator. """ - def wrapper(*args: Any, **kwargs: Any) -> Union[Literal[True], ValidationFailure]: + def wrapper(*args: Any, **kwargs: Any): return ( True if func(*args, **kwargs)