Skip to content

Commit

Permalink
add pyupgrade to pre-commit checks
Browse files Browse the repository at this point in the history
  • Loading branch information
pacrob committed Dec 7, 2023
1 parent e3e0f44 commit a8cfd77
Show file tree
Hide file tree
Showing 20 changed files with 49 additions and 47 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,8 @@ repos:
hooks:
- id: mypy
exclude: 'tests/|fixtures/'
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: [--py38-plus]
6 changes: 4 additions & 2 deletions eth_utils/abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ def collapse_if_tuple(abi: Dict[str, Any]) -> str:
typ = abi["type"]
if not isinstance(typ, str):
raise TypeError(
"The 'type' must be a string, but got %r of type %s" % (typ, type(typ))
"The 'type' must be a string, but got {!r} of type {}".format(
typ, type(typ)
)
)
elif not typ.startswith("tuple"):
return typ
Expand All @@ -37,7 +39,7 @@ def collapse_if_tuple(abi: Dict[str, Any]) -> str:
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_dim = typ[5:]
collapsed = "({}){}".format(delimited, array_dim)
collapsed = f"({delimited}){array_dim}"

return collapsed

Expand Down
4 changes: 1 addition & 3 deletions eth_utils/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ def to_normalized_address(value: Union[AnyAddress, str, bytes]) -> HexAddress:
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
raise TypeError(f"Value must be any string, instead got type {type(value)}")
if is_address(hex_address):
return HexAddress(HexStr(hex_address))
else:
Expand Down
16 changes: 10 additions & 6 deletions eth_utils/applicators.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def apply_formatter_at_index(
) -> Generator[List[Any], None, None]:
if at_index + 1 > len(value):
raise IndexError(
"Not enough values in iterable to apply formatter. Got: {0}. "
"Need: {1}".format(len(value), at_index + 1)
"Not enough values in iterable to apply formatter. Got: {}. "
"Need: {}".format(len(value), at_index + 1)
)
for index, item in enumerate(value):
if index == at_index:
Expand Down Expand Up @@ -98,14 +98,18 @@ def apply_formatters_to_dict(
try:
yield key, formatters[key](item)
except ValueError as exc:
new_error_message = "Could not format invalid value %r as field %r" % (
item,
key,
new_error_message = (
"Could not format invalid value {!r} as field {!r}".format(
item,
key,
)
)
raise ValueError(new_error_message) from exc
except TypeError as exc:
new_error_message = (
"Could not format invalid type of %r for field %r" % (item, key)
"Could not format invalid type of {!r} for field {!r}".format(
item, key
)
)
raise TypeError(new_error_message) from exc
else:
Expand Down
6 changes: 3 additions & 3 deletions eth_utils/conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def to_hex(
return HexStr(hex(cast(int, primitive)))

raise TypeError(
"Unsupported type: '{0}'. Must be one of: bool, str, bytes, bytearray"
"Unsupported type: '{}'. Must be one of: bool, str, bytes, bytearray"
"or int.".format(repr(type(primitive)))
)

Expand Down Expand Up @@ -101,7 +101,7 @@ def to_int(
else:
raise TypeError(
"Invalid type. Expected one of int/bool/str/bytes/bytearray. Got "
"{0}".format(type(primitive))
"{}".format(type(primitive))
)


Expand Down Expand Up @@ -182,7 +182,7 @@ def hexstr_if_str(
hexstr_or_primitive
):
raise ValueError(
"when sending a str, it must be a hex string. Got: {0!r}".format(
"when sending a str, it must be a hex string. Got: {!r}".format(
hexstr_or_primitive
)
)
Expand Down
4 changes: 2 additions & 2 deletions eth_utils/currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
"Unknown unit. Must be one of {}".format("/".join(units.keys()))
)

if number == 0:
Expand All @@ -76,7 +76,7 @@ def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int:
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
"Unknown unit. Must be one of {}".format("/".join(units.keys()))
)

if is_integer(number) or is_string(number):
Expand Down
2 changes: 1 addition & 1 deletion eth_utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
T = TypeVar("T")


class combomethod(object):
class combomethod:
def __init__(self, method: Callable[..., Any]) -> None:
self.method = method

Expand Down
6 changes: 2 additions & 4 deletions eth_utils/hexadecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def encode_hex(value: AnyStr) -> HexStr:
def is_0x_prefixed(value: str) -> bool:
if not is_text(value):
raise TypeError(
"is_0x_prefixed requires text typed arguments. Got: {0}".format(repr(value))
f"is_0x_prefixed requires text typed arguments. Got: {repr(value)}"
)
return value.startswith(("0x", "0X"))

Expand All @@ -68,9 +68,7 @@ def is_hexstr(value: Any) -> bool:

def is_hex(value: Any) -> bool:
if not is_text(value):
raise TypeError(
"is_hex requires text typed arguments. Got: {0}".format(repr(value))
)
raise TypeError(f"is_hex requires text typed arguments. Got: {repr(value)}")
if not value:
return False
return _HEX_REGEXP.fullmatch(value) is not None
10 changes: 4 additions & 6 deletions eth_utils/humanize.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def humanize_seconds(seconds: Union[float, int]) -> str:

unit_values = _consume_leading_zero_units(_humanize_seconds(int(seconds)))

return "".join(
("{0}{1}".format(amount, unit) for amount, unit in take(3, unit_values))
)
return "".join((f"{amount}{unit}" for amount, unit in take(3, unit_values)))


SECOND = 1
Expand Down Expand Up @@ -91,7 +89,7 @@ def humanize_bytes(value: bytes) -> str:
value_as_hex = value.hex()
head = value_as_hex[:DISPLAY_HASH_CHARS]
tail = value_as_hex[-1 * DISPLAY_HASH_CHARS :]
return "{0}..{1}".format(head, tail)
return f"{head}..{tail}"


def humanize_hash(value: Hash32) -> str:
Expand All @@ -109,7 +107,7 @@ def humanize_ipfs_uri(uri: URI) -> str:
ipfs_hash = parsed.netloc
head = ipfs_hash[:DISPLAY_HASH_CHARS]
tail = ipfs_hash[-1 * DISPLAY_HASH_CHARS :]
return "ipfs://{0}..{1}".format(head, tail)
return f"ipfs://{head}..{tail}"


def is_ipfs_uri(value: Any) -> bool:
Expand Down Expand Up @@ -159,7 +157,7 @@ def _humanize_range(bounds: Tuple[int, int]) -> str:
if left == right:
return str(left)
else:
return "{left}-{right}".format(left=left, right=right)
return f"{left}-{right}"


def humanize_integer_sequence(values_iter: Iterable[int]) -> str:
Expand Down
2 changes: 1 addition & 1 deletion eth_utils/module_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def import_string(dotted_path: str) -> Any:
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
msg = 'Module "{}" does not define a "{}" attribute/class'.format(
module_path,
class_name,
)
Expand Down
1 change: 0 additions & 1 deletion eth_utils/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def initialize_network_objects() -> List[Network]:
)
with open(
os.path.join(networks_json_path, "eth_networks.json"),
"r",
encoding="UTF-8",
) as open_file:
network_data = json.load(open_file)
Expand Down
1 change: 1 addition & 0 deletions newsfragments/261.breaking.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Drop python 3.7 support
1 change: 1 addition & 0 deletions newsfragments/261.internal.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Merge updates from the project template, notably: use ``pre-commit`` for linting and change the name of the ``master`` branch to ``main``
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import (
find_packages,
setup,
Expand Down
2 changes: 0 additions & 2 deletions tests/conversion-utils/test_conversions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding=utf-8

import pytest

from eth_utils import (
Expand Down
2 changes: 1 addition & 1 deletion tests/currency-utils/test_currency_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def make_ether_string_value(amount_in_wei):
whole_part = s_amount_in_wei[:-18] or "0"
decimal_part = s_amount_in_wei[-18:]

s_amount_in_ether = "{0}.{1}".format(
s_amount_in_ether = "{}.{}".format(
whole_part, decimal_part.zfill(18).rstrip("0")
).rstrip(".")
return s_amount_in_ether
Expand Down
6 changes: 3 additions & 3 deletions tests/curried-utils/test_curried.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ def should_curry(value):
return nargs == 1 and enhanced_has_keywords(value)

def curry_namespace(ns):
return dict(
(name, curry(f) if should_curry(f) else f)
return {
name: curry(f) if should_curry(f) else f
for name, f in ns.items()
if "__" not in name
)
}

all_auto_curried = curry_namespace(vars(eth_utils))

Expand Down
3 changes: 1 addition & 2 deletions tests/functional-utils/test_return_value_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@


def yield_things(*things):
for thing in things:
yield thing
yield from things


def test_to_tuple():
Expand Down
4 changes: 2 additions & 2 deletions tests/logging-utils/test_DEBUG2_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_caching_of_debug2_when_disabled(caplog, DEBUG2_installed):
caplog.set_level(DEBUG2_LEVEL_NUM, "testing")

# we need a unique logger because loggers are cached
logger = logging.getLogger("testing-{}".format(uuid.uuid4()))
logger = logging.getLogger(f"testing-{uuid.uuid4()}")

assert logger.isEnabledFor(DEBUG2_LEVEL_NUM) is False

Expand Down Expand Up @@ -71,7 +71,7 @@ def test_caching_of_debug2_when_enabled(caplog, DEBUG2_installed):
caplog.set_level(DEBUG2_LEVEL_NUM, "testing")

# we need a unique logger because loggers are cached
logger = logging.getLogger("testing-{}".format(uuid.uuid4()))
logger = logging.getLogger(f"testing-{uuid.uuid4()}")

assert logger.isEnabledFor(DEBUG2_LEVEL_NUM) is False
logger.setLevel(DEBUG2_LEVEL_NUM)
Expand Down
14 changes: 7 additions & 7 deletions tests/logging-utils/test_get_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,35 @@ class CustomLogger(logging.Logger):


def test_get_logger_with_no_class():
path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
logger = get_logger(path)
assert isinstance(logger, logging.Logger)
assert logger.name == path


def test_get_logger_with_default_class():
path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
logger = get_logger(path, logging.Logger)
assert isinstance(logger, logging.Logger)
assert logger.name == path


def test_get_logger_with_CustomLogger():
path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
logger = get_logger(path, CustomLogger)
assert isinstance(logger, CustomLogger)
assert logger.name == path


def test_get_extended_debug_logger():
path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
logger = get_extended_debug_logger(path)
assert isinstance(logger, ExtendedDebugLogger)
assert logger.name == path


def test_get_extended_debug_logger_if_other_logger_in_cache():
path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
normal_logger = get_logger(path)
assert not isinstance(normal_logger, ExtendedDebugLogger)
assert normal_logger.name == path
Expand All @@ -55,15 +55,15 @@ def test_get_extended_debug_logger_if_other_logger_in_cache():
def test_get_logger_preserves_logging_module_config():
assert logging.getLoggerClass() is logging.Logger

path = "testing.{0}".format(uuid.uuid4())
path = f"testing.{uuid.uuid4()}"
logger = get_logger(path, CustomLogger)
assert isinstance(logger, CustomLogger)

assert logging.getLoggerClass() is logging.Logger


def test_extended_debug_logger_pickling():
name = "testing.{0}".format(uuid.uuid4())
name = f"testing.{uuid.uuid4()}"
extended_logger = get_extended_debug_logger(name)
pickled = pickle.dumps(extended_logger)

Expand Down

0 comments on commit a8cfd77

Please sign in to comment.