Skip to content

Commit

Permalink
update typing for new mypy version
Browse files Browse the repository at this point in the history
  • Loading branch information
pacrob committed Dec 7, 2023
1 parent 086f4f5 commit e3e0f44
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 74 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ repos:
rev: v1.5.1
hooks:
- id: mypy
exclude: 'tests/|eth_utils/|fixtures/'
exclude: 'tests/|fixtures/'
16 changes: 3 additions & 13 deletions eth_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
try:
from importlib.metadata import (
version as __version,
)
except ImportError:
# Python 3.7
def __version(package_name: str) -> str: # type: ignore
from pkg_resources import (
get_distribution,
)

return get_distribution(package_name).version

from importlib.metadata import (
version as __version,
)

from .abi import (
event_abi_to_log_topic,
Expand Down
2 changes: 1 addition & 1 deletion eth_utils/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right)
return bool(to_normalized_address(left) == to_normalized_address(right))


def to_checksum_address(value: Union[AnyAddress, str, bytes]) -> ChecksumAddress:
Expand Down
26 changes: 17 additions & 9 deletions eth_utils/conversions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import (
Callable,
Optional,
TypeVar,
Union,
cast,
)

from eth_typing import (
Expand Down Expand Up @@ -34,7 +36,9 @@

@validate_conversion_arguments
def to_hex(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
primitive: Optional[Primitives] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None,
) -> HexStr:
"""
Auto converts any supported value into its hex representation.
Expand All @@ -59,7 +63,7 @@ def to_hex(
)

if is_integer(primitive):
return HexStr(hex(primitive))
return HexStr(hex(cast(int, primitive)))

raise TypeError(
"Unsupported type: '{0}'. Must be one of: bool, str, bytes, bytearray"
Expand All @@ -69,7 +73,9 @@ def to_hex(

@validate_conversion_arguments
def to_int(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
primitive: Optional[Primitives] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None,
) -> int:
"""
Converts value to its integer representation.
Expand Down Expand Up @@ -101,7 +107,9 @@ def to_int(

@validate_conversion_arguments
def to_bytes(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
primitive: Optional[Primitives] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None,
) -> bytes:
if is_boolean(primitive):
return b"\x01" if primitive else b"\x00"
Expand All @@ -113,9 +121,7 @@ def to_bytes(
return to_bytes(hexstr=to_hex(primitive))
elif hexstr is not None:
if len(hexstr) % 2:
# type check ignored here because casting an
# Optional arg to str is not possible
hexstr = "0x0" + remove_0x_prefix(hexstr) # type: ignore
hexstr = cast(HexStr, "0x0" + remove_0x_prefix(hexstr))
return decode_hex(hexstr)
elif text is not None:
return text.encode("utf-8")
Expand All @@ -127,7 +133,9 @@ def to_bytes(

@validate_conversion_arguments
def to_text(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
primitive: Optional[Primitives] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None,
) -> str:
if hexstr is not None:
return to_bytes(hexstr=hexstr).decode("utf-8")
Expand All @@ -138,7 +146,7 @@ def to_text(
elif isinstance(primitive, (bytes, bytearray)):
return primitive.decode("utf-8")
elif is_integer(primitive):
byte_encoding = int_to_big_endian(primitive)
byte_encoding = int_to_big_endian(cast(int, primitive))
return to_text(byte_encoding)
raise TypeError("Expected an int, bytes, bytearray or hexstr.")

Expand Down
7 changes: 5 additions & 2 deletions eth_utils/crypto.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import (
Optional,
Union,
)

Expand All @@ -12,6 +13,8 @@


def keccak(
primitive: Union[bytes, int, bool] = None, hexstr: str = None, text: str = None
primitive: Optional[Union[bytes, int, bool]] = None,
hexstr: Optional[str] = None,
text: Optional[str] = None,
) -> bytes:
return keccak_256(to_bytes(primitive, hexstr, text))
return bytes(keccak_256(to_bytes(primitive, hexstr, text)))
50 changes: 25 additions & 25 deletions eth_utils/curried/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# flake8: noqa
from typing import (
Any,
Callable,
Expand Down Expand Up @@ -111,35 +110,35 @@
def apply_formatter_if(
condition: Callable[..., bool]
) -> Callable[[Callable[..., TReturn]], Callable[[TValue], Union[TReturn, TValue]]]:
...
pass


@overload
def apply_formatter_if(
condition: Callable[..., bool], formatter: Callable[..., TReturn]
) -> Callable[[TValue], Union[TReturn, TValue]]:
...
pass


@overload
def apply_formatter_if(
condition: Callable[..., bool], formatter: Callable[..., TReturn], value: TValue
) -> Union[TReturn, TValue]:
...
pass


# This is just a stub to appease mypy, it gets overwritten later
def apply_formatter_if(
def apply_formatter_if( # type: ignore
condition: Callable[..., bool],
formatter: Callable[..., TReturn] = None,
value: TValue = None,
formatter: Optional[Callable[..., TReturn]] = None,
value: Optional[TValue] = None,
) -> Union[
Callable[[Callable[..., TReturn]], Callable[[TValue], Union[TReturn, TValue]]],
Callable[[TValue], Union[TReturn, TValue]],
TReturn,
TValue,
]:
...
pass


@overload
Expand All @@ -162,11 +161,11 @@ def apply_one_of_formatters(


# This is just a stub to appease mypy, it gets overwritten later
def apply_one_of_formatters(
def apply_one_of_formatters( # type: ignore
formatter_condition_pairs: Sequence[
Tuple[Callable[..., bool], Callable[..., TReturn]]
],
value: TValue = None,
value: Optional[TValue] = None,
) -> TReturn:
...

Expand All @@ -186,8 +185,8 @@ def hexstr_if_str(


# This is just a stub to appease mypy, it gets overwritten later
def hexstr_if_str(
to_type: Callable[..., TReturn], to_format: Union[bytes, int, str] = None
def hexstr_if_str( # type: ignore
to_type: Callable[..., TReturn], to_format: Optional[Union[bytes, int, str]] = None
) -> TReturn:
...

Expand All @@ -207,8 +206,9 @@ def text_if_str(


# This is just a stub to appease mypy, it gets overwritten later
def text_if_str(
to_type: Callable[..., TReturn], text_or_primitive: Union[bytes, int, str] = None
def text_if_str( # type: ignore
to_type: Callable[..., TReturn],
text_or_primitive: Optional[Union[bytes, int, str]] = None,
) -> TReturn:
...

Expand All @@ -223,36 +223,36 @@ def apply_formatters_to_dict(
@overload
def apply_formatters_to_dict(
formatters: Dict[Any, Any], value: Dict[Any, Any]
) -> TReturn:
) -> Dict[Any, Any]:
...


# This is just a stub to appease mypy, it gets overwritten later
def apply_formatters_to_dict(
def apply_formatters_to_dict( # type: ignore
formatters: Dict[Any, Any], value: Optional[Dict[Any, Any]] = None
) -> TReturn:
) -> Dict[Any, Any]:
...


apply_formatter_at_index = curry(apply_formatter_at_index)
apply_formatter_if = curry(non_curried_apply_formatter_if)
apply_formatter_if = curry(non_curried_apply_formatter_if) # noqa: F811
apply_formatter_to_array = curry(apply_formatter_to_array)
apply_formatters_to_dict = curry(non_curried_apply_formatters_to_dict)
apply_formatters_to_dict = curry(non_curried_apply_formatters_to_dict) # noqa: F811
apply_formatters_to_sequence = curry(apply_formatters_to_sequence)
apply_key_map = curry(apply_key_map)
apply_one_of_formatters = curry(non_curried_apply_one_of_formatters)
apply_one_of_formatters = curry(non_curried_apply_one_of_formatters) # noqa: F811
from_wei = curry(from_wei)
get_logger = curry(get_logger)
hexstr_if_str = curry(non_curried_hexstr_if_str)
hexstr_if_str = curry(non_curried_hexstr_if_str) # noqa: F811
is_same_address = curry(is_same_address)
text_if_str = curry(non_curried_text_if_str)
text_if_str = curry(non_curried_text_if_str) # noqa: F811
to_wei = curry(to_wei)
clamp = curry(clamp)

# Delete any methods and classes that are not intended to be importable from
# eth_utils.curried
# We do this approach instead of __all__ because this approach actually prevents
# importing the wrong thing, while __all__ only affects `from eth_utils.curried import *`
# `eth_utils.curried`. We do this approach instead of __all__ because this approach
# actually prevents importing the wrong thing, while __all__ only affects
# `from eth_utils.curried import *`
del Any
del Callable
del Dict
Expand Down
7 changes: 5 additions & 2 deletions eth_utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Any,
Callable,
Dict,
Optional,
Type,
TypeVar,
)
Expand All @@ -19,7 +20,9 @@ class combomethod(object):
def __init__(self, method: Callable[..., Any]) -> None:
self.method = method

def __get__(self, obj: T = None, objtype: Type[T] = None) -> Callable[..., Any]:
def __get__(
self, obj: Optional[T] = None, objtype: Optional[Type[T]] = None
) -> Callable[..., Any]:
@functools.wraps(self.method)
def _wrapper(*args: Any, **kwargs: Any) -> Any:
if obj is not None:
Expand Down Expand Up @@ -93,7 +96,7 @@ def return_arg_type(at_position: int) -> Callable[..., Callable[..., T]]:

def decorator(to_wrap: Callable[..., Any]) -> Callable[..., T]:
@functools.wraps(to_wrap)
def wrapper(*args: Any, **kwargs: Any) -> T:
def wrapper(*args: Any, **kwargs: Any) -> T: # type: ignore
result = to_wrap(*args, **kwargs)
ReturnType = type(args[at_position])
return ReturnType(result) # type: ignore
Expand Down
18 changes: 6 additions & 12 deletions eth_utils/logging.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import contextlib
from functools import (
cached_property,
)
import logging
import sys
from typing import (
Any,
Dict,
Iterator,
Tuple,
Type,
TypeVar,
Union,
cast,
)

from .toolz import (
assoc,
)

if sys.version_info < (3, 8):
from cached_property import (
cached_property,
)
else:
from functools import (
cached_property,
)

DEBUG2_LEVEL_NUM = 8

TLogger = TypeVar("TLogger", bound=logging.Logger)
Expand Down Expand Up @@ -59,7 +53,7 @@ def setup_DEBUG2_logging() -> None:
"""
if not hasattr(logging, "DEBUG2"):
logging.addLevelName(DEBUG2_LEVEL_NUM, "DEBUG2")
logging.DEBUG2 = DEBUG2_LEVEL_NUM
logging.DEBUG2 = DEBUG2_LEVEL_NUM # type: ignore


@contextlib.contextmanager
Expand All @@ -72,7 +66,7 @@ def _use_logger_class(logger_class: Type[logging.Logger]) -> Iterator[None]:
logging.setLoggerClass(original_logger_class)


def get_logger(name: str, logger_class: Type[TLogger] = None) -> TLogger:
def get_logger(name: str, logger_class: Union[Type[TLogger], None] = None) -> TLogger:
if logger_class is None:
return cast(TLogger, logging.getLogger(name))
else:
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
],
"test": [
"hypothesis>=4.43.0",
"mypy==1.5.1",
"pytest>=7.0.0",
"pytest-xdist>=2.4.0",
],
Expand Down
Loading

0 comments on commit e3e0f44

Please sign in to comment.