Skip to content

Commit

Permalink
convert format strings that pyupgrade can't do
Browse files Browse the repository at this point in the history
  • Loading branch information
pacrob committed Dec 13, 2023
1 parent 048df36 commit d609ffb
Show file tree
Hide file tree
Showing 16 changed files with 50 additions and 76 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,13 @@ python update_networks.py
If there are new networks they will appear in the JSON file. After checking the updates,
open a PR to make them available in a new release.

````
### Release setup

To release a new version:

```sh
make release bump=$$VERSION_PART_TO_BUMP$$
````
```

#### How to bumpversion

Expand Down
14 changes: 5 additions & 9 deletions eth_utils/abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,13 @@ 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 {}".format(
typ, type(typ)
)
f"The 'type' must be a string, but got {repr(typ)} of type {type(typ)}"
)
elif not typ.startswith("tuple"):
return typ

delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# 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 = f"({delimited}){array_dim}"
Expand All @@ -45,12 +43,10 @@ def collapse_if_tuple(abi: Dict[str, Any]) -> str:


def _abi_to_signature(abi: Dict[str, Any]) -> str:
function_signature = "{fn_name}({fn_input_types})".format(
fn_name=abi["name"],
fn_input_types=",".join(
[collapse_if_tuple(abi_input) for abi_input in abi.get("inputs", [])]
),
fn_input_types = ",".join(
[collapse_if_tuple(abi_input) for abi_input in abi.get("inputs", [])]
)
function_signature = f"{abi['name']}({fn_input_types})"
return function_signature


Expand Down
5 changes: 2 additions & 3 deletions eth_utils/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ def to_normalized_address(value: Union[AnyAddress, str, bytes]) -> HexAddress:
return HexAddress(HexStr(hex_address))
else:
raise ValueError(
"Unknown format {!r}, attempted to normalize to {!r}".format(
value, hex_address
)
f"Unknown format {repr(value)}, attempted to normalize to "
f"{repr(hex_address)}"
)


Expand Down
27 changes: 9 additions & 18 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: {}. "
"Need: {}".format(len(value), at_index + 1)
f"Not enough values in iterable to apply formatter. Got: {len(value)}. "
f"Need: {at_index + 1}"
)
for index, item in enumerate(value):
if index == at_index:
Expand Down Expand Up @@ -65,15 +65,13 @@ def apply_formatters_to_sequence(
) -> Generator[List[Any], None, None]:
if len(formatters) > len(sequence):
raise IndexError(
"Too many formatters for sequence: {} formatters for {!r}".format(
len(formatters), sequence
)
f"Too many formatters for sequence: {len(formatters)} formatters for "
f"{repr(sequence)}"
)
elif len(formatters) < len(sequence):
raise IndexError(
"Too few formatters for sequence: {} formatters for {!r}".format(
len(formatters), sequence
)
f"Too few formatters for sequence: {len(formatters)} formatters for "
f"{repr(sequence)}"
)
else:
for formatter, item in zip(formatters, sequence):
Expand All @@ -99,17 +97,12 @@ def apply_formatters_to_dict(
yield key, formatters[key](item)
except ValueError as exc:
new_error_message = (
"Could not format invalid value {!r} as field {!r}".format(
item,
key,
)
f"Could not format invalid value {repr(item)} as field {repr(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}".format(
item, key
)
f"Could not format invalid type {repr(item)} as field {repr(key)}"
)
raise TypeError(new_error_message) from exc
else:
Expand Down Expand Up @@ -148,9 +141,7 @@ def apply_key_map(
)
if key_conflicts:
raise KeyError(
"Could not apply key map due to conflicting key(s): {}".format(
key_conflicts
)
f"Could not apply key map due to conflicting key(s): {key_conflicts}"
)

for key, item in value.items():
Expand Down
13 changes: 6 additions & 7 deletions eth_utils/conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ def to_hex(
return HexStr(hex(cast(int, primitive)))

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


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


Expand Down Expand Up @@ -182,9 +182,8 @@ def hexstr_if_str(
hexstr_or_primitive
):
raise ValueError(
"when sending a str, it must be a hex string. Got: {!r}".format(
hexstr_or_primitive
)
"when sending a str, it must be a hex string. "
f"Got: {repr(hexstr_or_primitive)}"
)
return to_type(hexstr=hexstr_or_primitive)
else:
Expand Down
10 changes: 3 additions & 7 deletions eth_utils/currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {}".format("/".join(units.keys()))
)
raise ValueError(f"Unknown unit. Must be one of {'/'.join(units.keys())}")

if number == 0:
return 0
Expand All @@ -75,9 +73,7 @@ def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int:
Takes a number of a unit and converts it to wei.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {}".format("/".join(units.keys()))
)
raise ValueError(f"Unknown unit. Must be one of {'/'.join(units.keys())}")

if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
Expand All @@ -86,7 +82,7 @@ def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int:
elif isinstance(number, decimal.Decimal):
d_number = number
else:
raise TypeError("Unsupported type. Must be one of integer, float, or string")
raise TypeError("Unsupported type. Must be one of integer, float, or string")

s_number = str(number)
unit_value = units[unit.lower()]
Expand Down
6 changes: 3 additions & 3 deletions eth_utils/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@

def pip_freeze() -> str:
result = subprocess.run("python -m pip freeze".split(), stdout=subprocess.PIPE)
return "python -m pip freeze result:\n%s" % result.stdout.decode()
return f"python -m pip freeze result:\n{result.stdout.decode()}"


def python_version() -> str:
return "Python version:\n%s" % sys.version
return f"Python version:\n{sys.version}"


def platform_info() -> str:
return "Operating System: %s" % platform.platform()
return f"Operating System: {platform.platform()}"


def get_environment_summary() -> str:
Expand Down
8 changes: 4 additions & 4 deletions eth_utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def _assert_one_val(*args: T, **kwargs: T) -> None:
if not _has_one_val(*args, **kwargs):
raise TypeError(
"Exactly one of the passed values can be specified. "
"Instead, values were: %r, %r" % (args, kwargs)
f"Instead, values were: {repr(args)}, {repr(kwargs)}"
)


Expand All @@ -56,15 +56,15 @@ def _assert_hexstr_or_text_kwarg_is_text_type(**kwargs: T) -> None:
if not _hexstr_or_text_kwarg_is_text_type(**kwargs):
raise TypeError(
"Arguments passed as hexstr or text must be of text type. "
"Instead, value was: %r" % (repr(next(iter(list(kwargs.values())))))
f"Instead, value was: {(repr(next(iter(list(kwargs.values())))))}"
)


def _validate_supported_kwarg(kwargs: Any) -> None:
if next(iter(kwargs)) not in ["primitive", "hexstr", "text"]:
raise TypeError(
"Kwarg must be 'primitive', 'hexstr', or 'text'. "
"Instead, kwarg was: %r" % (next(iter(kwargs)))
f"Instead, kwarg was: {repr((next(iter(kwargs))))}"
)


Expand Down Expand Up @@ -124,7 +124,7 @@ def wrapped(*args: Any, **kwargs: Any) -> T:
raise old_to_new_exceptions[type(err)](err) from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
f"could not look up new exception to use for {repr(err)}"
) from err

return wrapped
Expand Down
4 changes: 2 additions & 2 deletions eth_utils/humanize.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def humanize_hash(value: Hash32) -> str:
def humanize_ipfs_uri(uri: URI) -> str:
if not is_ipfs_uri(uri):
raise TypeError(
"%s does not look like a valid IPFS uri. Currently, "
"only CIDv0 hash schemes are supported." % uri
f"{uri} does not look like a valid IPFS uri. Currently, "
"only CIDv0 hash schemes are supported."
)

parsed = parse.urlparse(uri)
Expand Down
6 changes: 3 additions & 3 deletions eth_utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def get_logger(name: str, logger_class: Union[Type[TLogger], None] = None) -> TL
return cast(TLogger, logging.getLogger(name))
else:
with _use_logger_class(logger_class):
# The logging module caches logger instances. The following code
# The logging module caches logger instances. The following code
# ensures that if there is a cached instance that we don't
# accidentally return the incorrect logger type because the logging
# module does not *update* the cached instance in the event that
Expand Down Expand Up @@ -135,7 +135,7 @@ def meta_compat(


class _BaseHasLogger(metaclass=HasLoggerMeta):
# This class exists to a allow us to define the type of the logger. Once
# This class exists to a allow us to define the type of the logger. Once
# python3.5 is deprecated this can be removed in favor of a simple type
# annotation on the main class.
logger = logging.Logger("") # type: logging.Logger
Expand All @@ -149,7 +149,7 @@ class HasLogger(_BaseHasLogger):


class _BaseHasExtendedDebugLogger(metaclass=HasExtendedDebugLoggerMeta): # type: ignore
# This class exists to a allow us to define the type of the logger. Once
# This class exists to a allow us to define the type of the logger. Once
# python3.5 is deprecated this can be removed in favor of a simple type
# annotation on the main class.
logger = ExtendedDebugLogger("") # type: ExtendedDebugLogger
Expand Down
7 changes: 2 additions & 5 deletions eth_utils/module_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,13 @@ def import_string(dotted_path: str) -> Any:
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
msg = f"{dotted_path} doesn't look like a module path"
raise ImportError(msg)

module = import_module(module_path)

try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "{}" does not define a "{}" attribute/class'.format(
module_path,
class_name,
)
msg = f'Module "{module_path}" does not define a "{class_name}" attribute/class'
raise ImportError(msg)
4 changes: 2 additions & 2 deletions eth_utils/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ def __gt__(self, other: Any) -> bool:

def clamp(lower_bound: TValue, upper_bound: TValue, value: TValue) -> TValue:
# The `mypy` ignore statements here are due to doing a comparison of
# `Union` types which isn't allowed. (per cburgdorf). This approach was
# `Union` types which isn't allowed. (per cburgdorf). This approach was
# chosen over using `typing.overload` to define multiple signatures for
# each comparison type here since the added value of "proper" typing
# doesn't seem to justify the complexity of having a bunch of different
# signatures defined. The external library perspective on this function
# signatures defined. The external library perspective on this function
# should still be adequate under this approach
if value < lower_bound: # type: ignore
return lower_bound
Expand Down
4 changes: 1 addition & 3 deletions tests/currency-utils/test_currency_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +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 = "{}.{}".format(
whole_part, decimal_part.zfill(18).rstrip("0")
).rstrip(".")
s_amount_in_ether = f"{whole_part}.{decimal_part.zfill(18).rstrip('0')}".rstrip(".")
return s_amount_in_ether


Expand Down
8 changes: 4 additions & 4 deletions tests/curried-utils/test_curried.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def curry_namespace(ns):
if inferred_namespace != curried_namespace:
missing = set(inferred_namespace) - set(curried_namespace)
if missing:
to_insert = sorted("%s," % f for f in missing)
to_insert = sorted(f"{f}," for f in missing)
raise AssertionError(
"There are missing functions in eth_utils.curried:\n"
+ "\n".join(to_insert)
Expand All @@ -75,7 +75,7 @@ def curry_namespace(ns):
unequal = valfilter(lambda x: x[0] != x[1], unequal)
to_curry = keyfilter(lambda x: should_curry(getattr(eth_utils, x)), unequal)
if to_curry:
to_curry_formatted = sorted("{0} = curry({0})".format(f) for f in to_curry)
to_curry_formatted = sorted(f"{f} = curry({f})" for f in to_curry)
raise AssertionError(
"There are missing functions to curry in eth_utils.curried:\n"
+ "\n".join(to_curry_formatted)
Expand All @@ -88,6 +88,6 @@ def curry_namespace(ns):
)
else:
raise AssertionError(
"unexplained difference between %r and %r"
% (inferred_namespace, curried_namespace)
f"unexplained difference between {repr(inferred_namespace)} and "
f"{repr(curried_namespace)}"
)
4 changes: 2 additions & 2 deletions tests/decorator-utils/test_combomethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class _Getter:
@combomethod
def get(combo):
if isinstance(combo, type):
return "%d by class" % combo.val
return f"{combo.val} by class"
elif isinstance(combo, _Getter):
return "%d by instance" % combo.val
return f"{combo.val} by instance"
else:
raise TypeError("Unreachable, unless you really monkey around")

Expand Down
2 changes: 1 addition & 1 deletion tests/type-checks/mypy_typing_of_has_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class VerifyGenericWithLoggerTypingInteger(VerifyGenericWithLoggerTyping[int]):

int_value = VerifyGenericWithLoggerTypingInteger.return_T(1234)

# mypy should be angry about passing a non-integer into this function. We test
# mypy should be angry about passing a non-integer into this function. We test
# this by using an ignore comment relying on our type checking settings to warn
# on un-used ignore statements
VerifyGenericWithLoggerTypingInteger.return_T("not-an-integer") # type: ignore

0 comments on commit d609ffb

Please sign in to comment.