From d061fe2345a7bcb47f7474c094a10714cdf6d483 Mon Sep 17 00:00:00 2001 From: Harmouch101 Date: Wed, 2 Mar 2022 20:19:05 +0200 Subject: [PATCH] :broom: clean python2 syntax. Signed-off-by: Harmouch101 --- docs/conf.py | 16 ++++++++-------- docs/examples.rst | 15 +++++---------- ens/main.py | 13 +++++-------- ens/utils.py | 2 +- tests/core/contracts/conftest.py | 2 +- .../test_contract_ambiguous_functions.py | 2 +- .../contracts/test_contract_call_interface.py | 2 +- tests/core/pm-module/test_ens_integration.py | 2 +- tests/core/providers/test_auto_provider.py | 8 ++++---- tests/core/utilities/test_formatters.py | 2 +- tests/ens/conftest.py | 2 +- web3/_utils/blocks.py | 2 +- web3/_utils/decorators.py | 2 +- web3/_utils/empty.py | 3 --- web3/_utils/encoding.py | 6 +++--- web3/_utils/ens.py | 2 +- web3/_utils/method_formatters.py | 6 ++---- web3/_utils/module_testing/eth_module.py | 4 ++-- web3/_utils/normalizers.py | 16 +++++++--------- web3/_utils/rpc_abi.py | 2 +- web3/_utils/transactions.py | 2 +- web3/_utils/validation.py | 2 +- web3/auto/infura/endpoints.py | 8 ++++---- web3/contract.py | 12 ++++++------ web3/datastructures.py | 10 +++------- web3/exceptions.py | 5 ++--- web3/main.py | 11 +++++------ web3/manager.py | 4 ++-- web3/middleware/validation.py | 17 ++++++----------- web3/providers/async_rpc.py | 8 +++----- web3/providers/auto.py | 6 ++---- web3/providers/ipc.py | 7 ++++--- web3/providers/rpc.py | 8 +++----- web3/providers/websocket.py | 4 ++-- web3/tools/pytest_ethereum/linker.py | 7 +++---- 35 files changed, 94 insertions(+), 126 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index fd50c0c203..a4f5ec9031 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -52,8 +52,8 @@ master_doc = 'index' # General information about the project. -project = u'Web3.py' -copyright = u'2018, Piper Merriam, Jason Carver' +project = 'Web3.py' +copyright = '2018, Piper Merriam, Jason Carver' __version__ = setup_version # The version info for the project you're documenting, acts as replacement for @@ -222,8 +222,8 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - ('index', 'Populus.tex', u'Populus Documentation', - u'Piper Merriam', 'manual'), + ('index', 'Populus.tex', 'Populus Documentation', + 'Piper Merriam', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -252,8 +252,8 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'web3', u'Web3.py Documentation', - [u'Piper Merriam'], 1) + ('index', 'web3', 'Web3.py Documentation', + ['Piper Merriam'], 1) ] # If true, show URL addresses after external links. @@ -266,8 +266,8 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'Web3.py', u'Web3.py Documentation', - u'Piper Merriam', 'Web3.py', 'Backend agnostic Ethereum client interactions.', + ('index', 'Web3.py', 'Web3.py Documentation', + 'Piper Merriam', 'Web3.py', 'Backend agnostic Ethereum client interactions.', 'Miscellaneous'), ] diff --git a/docs/examples.rst b/docs/examples.rst index e54ed70d43..83d41a6ee7 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -992,7 +992,7 @@ The script can be run with: ``python ./eventscanner.py `` # from our in-memory cache block_when = get_block_when(block_number) - logger.debug("Processing event %s, block:%d count:%d", evt["event"], evt["blockNumber"]) + logger.debug(f"Processing event {evt["event"]}, block: {evt["blockNumber"]} count: {evt["blockNumber"]}") processed = self.state.process_event(block_when, evt) all_processed.append(processed) @@ -1064,8 +1064,8 @@ The script can be run with: ``python ./eventscanner.py `` # Print some diagnostics to logs to try to fiddle with real world JSON-RPC API performance estimated_end_block = current_block + chunk_size logger.debug( - "Scanning token transfers for blocks: %d - %d, chunk size %d, last chunk scan took %f, last logs found %d", - current_block, estimated_end_block, chunk_size, last_scan_duration, last_logs_found) + f"Scanning token transfers for blocks: {current_block} - {estimated_end_block}, chunk size {chunk_size}, last chunk scan took {last_scan_duration}, last logs found {last_logs_found}" + ) start = time.time() actual_end_block, end_block_timestamp, new_entries = self.scan_chunk(current_block, estimated_end_block) @@ -1116,12 +1116,7 @@ The script can be run with: ``python ./eventscanner.py `` if i < retries - 1: # Give some more verbose info than the default middleware logger.warning( - "Retrying events for block range %d - %d (%d) failed with %s, retrying in %s seconds", - start_block, - end_block, - end_block-start_block, - e, - delay) + f"Retrying events for block range {start_block} - {end_block} ({end_block-start_block}) failed with {e} , retrying in {delay} seconds") # Decrease the `eth_getBlocks` range end_block = start_block + ((end_block - start_block) // 2) # Let the JSON-RPC to recover e.g. from restart @@ -1175,7 +1170,7 @@ The script can be run with: ``python ./eventscanner.py `` toBlock=to_block ) - logger.debug("Querying eth_getLogs with the following parameters: %s", event_filter_params) + logger.debug(f"Querying eth_getLogs with the following parameters: {event_filter_params}") # Call JSON-RPC API on your Ethereum node. # get_logs() returns raw AttributedDict entries diff --git a/ens/main.py b/ens/main.py index 928a3106a4..8578ff6de2 100644 --- a/ens/main.py +++ b/ens/main.py @@ -227,10 +227,8 @@ def setup_name( address = resolved elif resolved and address != resolved and resolved != EMPTY_ADDR_HEX: raise AddressMismatch( - "Could not set address %r to point to name, because the name resolves to %r. " - "To change the name for an existing address, call setup_address() first." % ( - address, resolved - ) + f"Could not set address {address!r} to point to name, because the name resolves to {resolved!r}. " + "To change the name for an existing address, call setup_address() first." ) if is_none_or_zero_address(address): address = self.owner(name) @@ -335,9 +333,8 @@ def _assert_control(self, account: ChecksumAddress, name: str, parent_owned: Optional[str] = None) -> None: if not address_in(account, self.w3.eth.accounts): raise UnauthorizedError( - "in order to modify %r, you must control account %r, which owns %r" % ( - name, account, parent_owned or name - ) + f"in order to modify {name!r}, you must control account" + f" {account!r}, which owns {parent_owned or name!r}" ) def _first_owner(self, name: str) -> Tuple[Optional[ChecksumAddress], Sequence[str], str]: @@ -374,7 +371,7 @@ def _claim_ownership( label_to_hash(label), owner ).transact(transact) - owned = "%s.%s" % (label, owned) + owned = f"{label}.{owned}" def _set_resolver( self, diff --git a/ens/utils.py b/ens/utils.py index 43c223b5e2..33fda9ee29 100644 --- a/ens/utils.py +++ b/ens/utils.py @@ -140,7 +140,7 @@ def sha3_text(val: Union[str, bytes]) -> HexBytes: def label_to_hash(label: str) -> HexBytes: label = normalize_name(label) if '.' in label: - raise ValueError("Cannot generate hash for label %r with a '.'" % label) + raise ValueError(f"Cannot generate hash for label {label!r} with a '.'") return Web3().keccak(text=label) diff --git a/tests/core/contracts/conftest.py b/tests/core/contracts/conftest.py index 2941572be8..91d01d5875 100644 --- a/tests/core/contracts/conftest.py +++ b/tests/core/contracts/conftest.py @@ -1010,7 +1010,7 @@ def invoke_contract(api_call_desig='call', tx_params={}): allowable_call_desig = ['call', 'transact', 'estimateGas', 'buildTransaction'] if api_call_desig not in allowable_call_desig: - raise ValueError("allowable_invoke_method must be one of: %s" % allowable_call_desig) + raise ValueError(f"allowable_invoke_method must be one of: {allowable_call_desig}") function = contract.functions[contract_function] result = getattr(function(*func_args, **func_kwargs), api_call_desig)(tx_params) diff --git a/tests/core/contracts/test_contract_ambiguous_functions.py b/tests/core/contracts/test_contract_ambiguous_functions.py index 69e15e4ff6..8f6c0b5ae2 100644 --- a/tests/core/contracts/test_contract_ambiguous_functions.py +++ b/tests/core/contracts/test_contract_ambiguous_functions.py @@ -153,7 +153,7 @@ def test_find_or_get_functions_by_type(w3, method, args, repr_func, expected): ( 'get_function_by_selector', (b'\x00' * (4 + 1), ), - r'expected value of size 4 bytes. Got: %s bytes' % (4 + 1), + f'expected value of size 4 bytes. Got: {(4 + 1)} bytes', ValueError ), ( diff --git a/tests/core/contracts/test_contract_call_interface.py b/tests/core/contracts/test_contract_call_interface.py index 6b1c1809b8..4e67c7d1cd 100644 --- a/tests/core/contracts/test_contract_call_interface.py +++ b/tests/core/contracts/test_contract_call_interface.py @@ -726,7 +726,7 @@ def test_reflect_fixed_value(fixed_reflection_contract, function, value): ('reflect_short_u', Decimal('0.01'), "no matching argument types"), ( 'reflect_short_u', - Decimal('1e-%d' % (DEFAULT_DECIMALS + 1)), + Decimal(f'1e-{DEFAULT_DECIMALS + 1}'), "no matching argument types", ), ('reflect_short_u', Decimal('25.4' + '9' * DEFAULT_DECIMALS), "no matching argument types"), diff --git a/tests/core/pm-module/test_ens_integration.py b/tests/core/pm-module/test_ens_integration.py index c6bd38b519..76dc64a1d6 100644 --- a/tests/core/pm-module/test_ens_integration.py +++ b/tests/core/pm-module/test_ens_integration.py @@ -20,7 +20,7 @@ def bytes32(val): if isinstance(val, int): result = to_bytes(val) else: - raise TypeError('val %r could not be converted to bytes') + raise TypeError(f'{val!r} could not be converted to bytes') return result.rjust(32, b'\0') diff --git a/tests/core/providers/test_auto_provider.py b/tests/core/providers/test_auto_provider.py index c0e30295f6..1647d5d502 100644 --- a/tests/core/providers/test_auto_provider.py +++ b/tests/core/providers/test_auto_provider.py @@ -108,7 +108,7 @@ def test_web3_auto_infura(monkeypatch, caplog, environ_name): w3 = infura.w3 assert isinstance(w3.provider, HTTPProvider) - expected_url = 'https://%s/v3/%s' % (infura.INFURA_MAINNET_DOMAIN, API_KEY) + expected_url = f'https://{infura.INFURA_MAINNET_DOMAIN}/v3/{API_KEY}' assert getattr(w3.provider, 'endpoint_uri') == expected_url @@ -117,7 +117,7 @@ def test_web3_auto_infura_websocket_default(monkeypatch, caplog, environ_name): monkeypatch.setenv('WEB3_INFURA_SCHEME', 'wss') API_KEY = 'aoeuhtns' monkeypatch.setenv(environ_name, API_KEY) - expected_url = 'wss://%s/ws/v3/%s' % (infura.INFURA_MAINNET_DOMAIN, API_KEY) + expected_url = f'wss://{infura.INFURA_MAINNET_DOMAIN}/ws/v3/{API_KEY}' importlib.reload(infura) assert len(caplog.record_tuples) == 0 @@ -145,7 +145,7 @@ def test_web3_auto_infura_websocket_with_secret(monkeypatch, caplog, environ_nam w3 = infura.w3 assert isinstance(w3.provider, WebsocketProvider) - expected_url = 'wss://:secret@%s/ws/v3/test' % (infura.INFURA_MAINNET_DOMAIN) + expected_url = f'wss://:secret@{infura.INFURA_MAINNET_DOMAIN}/ws/v3/test' assert getattr(w3.provider, 'endpoint_uri') == expected_url @@ -159,7 +159,7 @@ def test_web3_auto_infura_with_secret(monkeypatch, caplog, environ_name): w3 = infura.w3 assert isinstance(w3.provider, HTTPProvider) - expected_url = 'https://%s/v3/test' % (infura.INFURA_MAINNET_DOMAIN) + expected_url = f'https://{infura.INFURA_MAINNET_DOMAIN}/v3/test' expected_auth_value = ('', 'secret') assert getattr(w3.provider, 'endpoint_uri') == expected_url assert w3.provider.get_request_kwargs()['auth'] == expected_auth_value diff --git a/tests/core/utilities/test_formatters.py b/tests/core/utilities/test_formatters.py index 649578f7ce..45a56772f8 100644 --- a/tests/core/utilities/test_formatters.py +++ b/tests/core/utilities/test_formatters.py @@ -18,7 +18,7 @@ def square_int(x): return x -@pytest.mark.parametrize('non_collection', [1, 'abc', u'def', True, None]) +@pytest.mark.parametrize('non_collection', [1, 'abc', 'def', True, None]) def test_map_collection_on_non_collection(non_collection): assert map_collection(lambda x: x + 2, non_collection) == non_collection diff --git a/tests/ens/conftest.py b/tests/ens/conftest.py index 7a3d2044dd..a11c5ff7dd 100644 --- a/tests/ens/conftest.py +++ b/tests/ens/conftest.py @@ -34,7 +34,7 @@ def bytes32(val): if isinstance(val, int): result = Web3.toBytes(val) else: - raise TypeError('val %r could not be converted to bytes') + raise TypeError(f'{val!r} could not be converted to bytes') if len(result) < 32: return result.rjust(32, b'\0') else: diff --git a/web3/_utils/blocks.py b/web3/_utils/blocks.py index ac875f3c03..63ff37328c 100644 --- a/web3/_utils/blocks.py +++ b/web3/_utils/blocks.py @@ -31,7 +31,7 @@ def is_predefined_block_number(value: Any) -> bool: elif is_integer(value): return False else: - raise TypeError("unrecognized block reference: %r" % value) + raise TypeError(f"unrecognized block reference: {value!r}") return value_text in {"latest", "pending", "earliest"} diff --git a/web3/_utils/decorators.py b/web3/_utils/decorators.py index 63e14d9506..d93ff99277 100644 --- a/web3/_utils/decorators.py +++ b/web3/_utils/decorators.py @@ -24,7 +24,7 @@ def wrapped(*args: Any) -> Any: thread_id = threading.get_ident() thread_local_args = (thread_id,) + arg_instances if thread_local_args in to_wrap.__already_called: # type: ignore - raise ValueError('Recursively called %s with %r' % (to_wrap, args)) + raise ValueError(f'Recursively called {to_wrap} with {args!r}') to_wrap.__already_called[thread_local_args] = True # type: ignore try: wrapped_val = to_wrap(*args) diff --git a/web3/_utils/empty.py b/web3/_utils/empty.py index e6d299b3d6..1fb94fda60 100644 --- a/web3/_utils/empty.py +++ b/web3/_utils/empty.py @@ -7,8 +7,5 @@ class Empty: def __bool__(self) -> Literal[False]: return False - def __nonzero__(self) -> Literal[False]: - return False - empty = Empty() diff --git a/web3/_utils/encoding.py b/web3/_utils/encoding.py index 085cbf1378..d549c8f1f3 100644 --- a/web3/_utils/encoding.py +++ b/web3/_utils/encoding.py @@ -191,14 +191,14 @@ def _json_mapping_errors(self, mapping: Dict[Any, Any]) -> Iterable[str]: try: self._friendly_json_encode(val) except TypeError as exc: - yield "%r: because (%s)" % (key, exc) + yield f"{key!r}: because ({exc})" def _json_list_errors(self, iterable: Iterable[Any]) -> Iterable[str]: for index, element in enumerate(iterable): try: self._friendly_json_encode(element) except TypeError as exc: - yield "%d: because (%s)" % (index, exc) + yield f"{index}: because ({exc})" def _friendly_json_encode(self, obj: Dict[Any, Any], cls: Optional[Type[json.JSONEncoder]] = None) -> str: @@ -238,7 +238,7 @@ def to_4byte_hex(hex_or_str_or_bytes: Union[HexStr, str, bytes, int]) -> HexStr: byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes) if len(byte_str) > 4: raise ValueError( - 'expected value of size 4 bytes. Got: %d bytes' % len(byte_str) + f'expected value of size 4 bytes. Got: {len(byte_str)} bytes' ) hex_str = encode_hex(byte_str) return pad_hex(hex_str, size_of_4bytes) diff --git a/web3/_utils/ens.py b/web3/_utils/ens.py index f924d306d7..c5ba63deb5 100644 --- a/web3/_utils/ens.py +++ b/web3/_utils/ens.py @@ -46,7 +46,7 @@ def validate_name_has_address(ens: ENS, name: str) -> ChecksumAddress: if addr: return addr else: - raise NameNotFound("Could not find address for name %r" % name) + raise NameNotFound(f"Could not find address for name {name!r}") class StaticENS: diff --git a/web3/_utils/method_formatters.py b/web3/_utils/method_formatters.py index 5105b5f0e0..7a1ff17a7b 100644 --- a/web3/_utils/method_formatters.py +++ b/web3/_utils/method_formatters.py @@ -123,7 +123,7 @@ def to_hexbytes( if isinstance(val, (str, int, bytes)): result = HexBytes(val) else: - raise TypeError("Cannot convert %r to HexBytes" % val) + raise TypeError(f"Cannot convert {val!r} to HexBytes") extra_bytes = len(result) - num_bytes if extra_bytes == 0 or (variable_length and extra_bytes < 0): @@ -132,9 +132,7 @@ def to_hexbytes( return HexBytes(result[extra_bytes:]) else: raise ValueError( - "The value %r is %d bytes, but should be %d" % ( - result, len(result), num_bytes - ) + f"The value {result!r} is {len(result)} bytes, but should be {num_bytes}" ) diff --git a/web3/_utils/module_testing/eth_module.py b/web3/_utils/module_testing/eth_module.py index a2e4b66ea9..f2fa5bee92 100644 --- a/web3/_utils/module_testing/eth_module.py +++ b/web3/_utils/module_testing/eth_module.py @@ -2739,7 +2739,7 @@ def test_eth_getTransactionByHash_contract_creation( ) -> None: transaction = w3.eth.get_transaction(math_contract_deploy_txn_hash) assert is_dict(transaction) - assert transaction['to'] is None, "to field is %r" % transaction['to'] + assert transaction['to'] is None, f"to field is {transaction['to']!r}" def test_eth_getTransactionByBlockHashAndIndex( self, w3: "Web3", block_with_txn: BlockData, mined_txn_hash: HexStr @@ -3140,7 +3140,7 @@ def test_eth_call_old_contract_state( assert default_call_result == 0 if pending_call_result != 1: - raise AssertionError("pending call result was %d instead of 1" % pending_call_result) + raise AssertionError(f"pending call result was {pending_call_result} instead of 1") def test_eth_uninstallFilter_deprecated(self, w3: "Web3") -> None: filter = w3.eth.filter({}) diff --git a/web3/_utils/normalizers.py b/web3/_utils/normalizers.py index fe0b07dd7d..25232e118c 100644 --- a/web3/_utils/normalizers.py +++ b/web3/_utils/normalizers.py @@ -146,9 +146,7 @@ def abi_bytes_to_hex( num_bytes = abi_type.sub if len(bytes_data) > num_bytes: raise ValueError( - "This value was expected to be at most %d bytes, but instead was %d: %r" % ( - (num_bytes, len(bytes_data), data) - ) + f"This value was expected to be at most {num_bytes} bytes, but instead was {len(bytes_data)}: {data!r}" ) padded = bytes_data.ljust(num_bytes, b'\0') @@ -204,18 +202,18 @@ def abi_ens_resolver(w3: "Web3", type_str: TypeStr, val: Any) -> Tuple[TypeStr, if type_str == 'address' and is_ens_name(val): if w3 is None: raise InvalidAddress( - "Could not look up name %r because no web3" - " connection available" % (val) + f"Could not look up name {val!r} because no web3" + " connection available" ) elif w3.ens is None: raise InvalidAddress( - "Could not look up name %r because ENS is" - " set to None" % (val) + f"Could not look up name {val!r} because ENS is" + " set to None" ) elif int(w3.net.version) != 1 and not isinstance(w3.ens, StaticENS): raise InvalidAddress( - "Could not look up name %r because web3 is" - " not connected to mainnet" % (val) + f"Could not look up name {val!r} because web3 is" + " not connected to mainnet" ) else: return type_str, validate_name_has_address(w3.ens, val) diff --git a/web3/_utils/rpc_abi.py b/web3/_utils/rpc_abi.py index 87b29e41bb..641497ef42 100644 --- a/web3/_utils/rpc_abi.py +++ b/web3/_utils/rpc_abi.py @@ -241,4 +241,4 @@ def abi_request_formatters( single_dict_formatter = apply_abi_formatters_to_dict(normalizers, abi_types) yield method, apply_formatter_at_index(single_dict_formatter, 0) else: - raise TypeError("ABI definitions must be a list or dictionary, got %r" % abi_types) + raise TypeError(f"ABI definitions must be a list or dictionary, got {abi_types!r}") diff --git a/web3/_utils/transactions.py b/web3/_utils/transactions.py index 8d9ca470df..638cb89d50 100644 --- a/web3/_utils/transactions.py +++ b/web3/_utils/transactions.py @@ -109,7 +109,7 @@ def fill_transaction_defaults(w3: "Web3", transaction: TxParams) -> TxParams: if callable(default_getter): if w3 is None: - raise ValueError("You must specify a '%s' value in the transaction" % key) + raise ValueError(f"You must specify a '{key}' value in the transaction") default_val = default_getter(w3, transaction) else: default_val = default_getter diff --git a/web3/_utils/validation.py b/web3/_utils/validation.py index 65fcb9f1c0..d59e788d61 100644 --- a/web3/_utils/validation.py +++ b/web3/_utils/validation.py @@ -205,5 +205,5 @@ def assert_one_val(*args: Any, **kwargs: Any) -> 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: {args!r}, {kwargs!r}" ) diff --git a/web3/auto/infura/endpoints.py b/web3/auto/infura/endpoints.py index c8de5c78d2..8531e3c023 100644 --- a/web3/auto/infura/endpoints.py +++ b/web3/auto/infura/endpoints.py @@ -56,10 +56,10 @@ def build_infura_url(domain: str) -> URI: secret = load_secret() if scheme == WEBSOCKET_SCHEME and secret != '': - return URI("%s://:%s@%s/ws/v3/%s" % (scheme, secret, domain, key)) + return URI(f"{scheme}://:{secret}@{domain}/ws/v3/{key}") elif scheme == WEBSOCKET_SCHEME and secret == '': - return URI("%s://%s/ws/v3/%s" % (scheme, domain, key)) + return URI(f"{scheme}://{domain}/ws/v3/{key}") elif scheme == HTTP_SCHEME: - return URI("%s://%s/v3/%s" % (scheme, domain, key)) + return URI(f"{scheme}://{domain}/v3/{key}") else: - raise ValidationError("Cannot connect to Infura with scheme %r" % scheme) + raise ValidationError(f"Cannot connect to Infura with scheme {scheme!r}") diff --git a/web3/contract.py b/web3/contract.py index 38e98b4152..c20d0e2156 100644 --- a/web3/contract.py +++ b/web3/contract.py @@ -425,7 +425,7 @@ def get_function_by_signature(self, signature: str) -> 'ContractFunction': if ' ' in signature: raise ValueError( 'Function signature should not contain any spaces. ' - 'Found spaces in input: %s' % signature + f'Found spaces in input: {signature}' ) def callable_check(fn_abi: ABIFunction) -> bool: @@ -715,9 +715,9 @@ def __prepared_function(self, *args: Any, **kwargs: Any) -> 'ContractFunction': modifier, modifier_dict = kwargs.popitem() if modifier not in self.ALLOWED_MODIFIERS: raise TypeError( - "The only allowed keyword arguments are: %s" % self.ALLOWED_MODIFIERS) + f"The only allowed keyword arguments are: {self.ALLOWED_MODIFIERS}") else: - raise TypeError("Use up to one keyword argument, one of: %s" % self.ALLOWED_MODIFIERS) + raise TypeError(f"Use up to one keyword argument, one of: {self.ALLOWED_MODIFIERS}") return getattr(self._function(*args), modifier)(modifier_dict) @@ -1099,11 +1099,11 @@ def factory(cls, class_name: str, **kwargs: Any) -> 'ContractFunction': def __repr__(self) -> str: if self.abi: - _repr = '' - return '' % self.fn_name + return f'' class ContractEvent: diff --git a/web3/datastructures.py b/web3/datastructures.py index 79f6cd59ec..7e2b183c2b 100644 --- a/web3/datastructures.py +++ b/web3/datastructures.py @@ -57,7 +57,7 @@ def __len__(self) -> int: return len(self.__dict__) def __repr__(self) -> str: - return self.__class__.__name__ + "(%r)" % self.__dict__ + return self.__class__.__name__ + f"({self.__dict__!r})" def _repr_pretty_(self, builder: Any, cycle: bool) -> None: """ @@ -158,12 +158,8 @@ def inject(self, element: TValue, name: Optional[TKey] = None, raise TypeError("The layer for insertion must be an int.") elif layer != 0 and layer != len(self._queue): raise NotImplementedError( - "You can only insert to the beginning or end of a %s, currently. " - "You tried to insert to %d, but only 0 and %d are permitted. " % ( - type(self), - layer, - len(self._queue), - ) + f"You can only insert to the beginning or end of a {type(self)}, currently. " + f"You tried to insert to {layer}, but only 0 and {len(self._queue)} are permitted. " ) self.add(element, name=name) diff --git a/web3/exceptions.py b/web3/exceptions.py index 3390275151..a6f84d7efc 100644 --- a/web3/exceptions.py +++ b/web3/exceptions.py @@ -52,9 +52,8 @@ class StaleBlockchain(Exception): def __init__(self, block: BlockData, allowable_delay: int) -> None: last_block_date = datetime.datetime.fromtimestamp(block["timestamp"]).strftime('%c') message = ( - "The latest block, #%d, is %d seconds old, but is only allowed to be %d s old. " - "The date of the most recent block is %s. Continue syncing and try again..." % - (block["number"], time.time() - block["timestamp"], allowable_delay, last_block_date) + f"The latest block, #{block['number']}, is {time.time() - block['timestamp']} seconds old, but is only allowed to be {allowable_delay} s old. " + f"The date of the most recent block is {last_block_date}. Continue syncing and try again..." ) super().__init__(message, block, allowable_delay) diff --git a/web3/main.py b/web3/main.py index acbac1b9a3..d0abd77709 100644 --- a/web3/main.py +++ b/web3/main.py @@ -292,12 +292,11 @@ def keccak(primitive: Optional[Primitives] = None, text: Optional[str] = None, return eth_utils_keccak(input_bytes) raise TypeError( - "You called keccak with first arg %r and keywords %r. You must call it with one of " - "these approaches: keccak(text='txt'), keccak(hexstr='0x747874'), " - "keccak(b'\\x74\\x78\\x74'), or keccak(0x747874)." % ( - primitive, - {'text': text, 'hexstr': hexstr} - ) + f"You called keccak with first arg {primitive!r} and keywords " + f"{{'text': {text!r}, 'hexstr': {hexstr!r}}}. You must call it " + "with one of these approaches: keccak(text='txt'), keccak " + "(hexstr='0x747874'), keccak(b'\\x74\\x78\\x74'), or kecca " + "(0x747874)." ) @combomethod diff --git a/web3/manager.py b/web3/manager.py index 1594c4dd6f..db5c6085b4 100644 --- a/web3/manager.py +++ b/web3/manager.py @@ -146,7 +146,7 @@ def _make_request( request_func = self.provider.request_func( self.w3, self.middleware_onion) - self.logger.debug("Making request. Method: %s", method) + self.logger.debug(f"Making request. Method: {method}") return request_func(method, params) async def _coro_make_request( @@ -156,7 +156,7 @@ async def _coro_make_request( request_func = await self.provider.request_func( # type: ignore self.w3, self.middleware_onion) - self.logger.debug("Making request. Method: %s", method) + self.logger.debug(f"Making request. Method: {method}") return await request_func(method, params) @staticmethod diff --git a/web3/middleware/validation.py b/web3/middleware/validation.py index 5fafce175b..23872858ef 100644 --- a/web3/middleware/validation.py +++ b/web3/middleware/validation.py @@ -59,11 +59,8 @@ def _validate_chain_id(web3_chain_id: int, chain_id: int) -> int: return chain_id else: raise ValidationError( - "The transaction declared chain ID %r, " - "but the connected node is on %r" % ( - chain_id, - web3_chain_id, - ) + f"The transaction declared chain ID {chain_id!r}, " + f"but the connected node is on {web3_chain_id!r}" ) @@ -73,13 +70,11 @@ def _check_extradata_length(val: Any) -> Any: result = HexBytes(val) if len(result) > MAX_EXTRADATA_LENGTH: raise ExtraDataLengthError( - "The field extraData is %d bytes, but should be %d. " - "It is quite likely that you are connected to a POA chain. " - "Refer to " + f"The field extraData is {len(result)} bytes, but should be " + f"{MAX_EXTRADATA_LENGTH}. It is quite likely that you are " + "connected to a POA chain. Refer to " "http://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority " - "for more details. The full extraData is: %r" % ( - len(result), MAX_EXTRADATA_LENGTH, result - ) + f"for more details. The full extraData is: {result!r}" ) return val diff --git a/web3/providers/async_rpc.py b/web3/providers/async_rpc.py index d3229c71de..dc80bfdedf 100644 --- a/web3/providers/async_rpc.py +++ b/web3/providers/async_rpc.py @@ -74,8 +74,7 @@ def get_request_headers(self) -> Dict[str, str]: } async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: - self.logger.debug("Making request HTTP. URI: %s, Method: %s", - self.endpoint_uri, method) + self.logger.debug(f"Making request HTTP. URI: {self.endpoint_uri}, Method: {method}") request_data = self.encode_rpc_request(method, params) raw_response = await async_make_post_request( self.endpoint_uri, @@ -83,7 +82,6 @@ async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: **self.get_request_kwargs() ) response = self.decode_rpc_response(raw_response) - self.logger.debug("Getting response HTTP. URI: %s, " - "Method: %s, Response: %s", - self.endpoint_uri, method, response) + self.logger.debug(f"Getting response HTTP. URI: {self.endpoint_uri}, " + f"Method: {method}, Response: {response}") return response diff --git a/web3/providers/auto.py b/web3/providers/auto.py index 9d351b3aec..9bc49b893b 100644 --- a/web3/providers/auto.py +++ b/web3/providers/auto.py @@ -55,10 +55,8 @@ def load_provider_from_uri( return WebsocketProvider(uri_string) else: raise NotImplementedError( - 'Web3 does not know how to connect to scheme %r in %r' % ( - uri.scheme, - uri_string, - ) + f'Web3 does not know how to connect to scheme {uri.scheme!r} ' + f'in {uri_string!r}' ) diff --git a/web3/providers/ipc.py b/web3/providers/ipc.py index 45faf63b61..c4b72b617e 100644 --- a/web3/providers/ipc.py +++ b/web3/providers/ipc.py @@ -52,7 +52,9 @@ def __init__(self, ipc_path: str) -> None: def __enter__(self) -> socket.socket: if not self.ipc_path: - raise FileNotFoundError("cannot connect to IPC socket at path: %r" % self.ipc_path) + raise FileNotFoundError("cannot connect to IPC socket at path: " + f"{self.ipc_path!r}" + ) if not self.sock: self.sock = self._open() @@ -231,8 +233,7 @@ def __str__(self) -> str: return f"<{self.__class__.__name__} {self.ipc_path}>" def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: - self.logger.debug("Making request IPC. Path: %s, Method: %s", - self.ipc_path, method) + self.logger.debug(f"Making request IPC. Path: {self.ipc_path}, Method: {method}") request = self.encode_rpc_request(method, params) with self._lock, self._socket as sock: diff --git a/web3/providers/rpc.py b/web3/providers/rpc.py index 0be744f71d..74c83eac7e 100644 --- a/web3/providers/rpc.py +++ b/web3/providers/rpc.py @@ -82,8 +82,7 @@ def get_request_headers(self) -> Dict[str, str]: } def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: - self.logger.debug("Making request HTTP. URI: %s, Method: %s", - self.endpoint_uri, method) + self.logger.debug(f"Making request HTTP. URI: {self.endpoint_uri}, Method: {method}") request_data = self.encode_rpc_request(method, params) raw_response = make_post_request( self.endpoint_uri, @@ -91,7 +90,6 @@ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: **self.get_request_kwargs() ) response = self.decode_rpc_response(raw_response) - self.logger.debug("Getting response HTTP. URI: %s, " - "Method: %s, Response: %s", - self.endpoint_uri, method, response) + self.logger.debug(f"Getting response HTTP. URI: {self.endpoint_uri}, " + f"Method: {method}, Response: {response}") return response diff --git a/web3/providers/websocket.py b/web3/providers/websocket.py index e999d56d3f..ef486ff49c 100644 --- a/web3/providers/websocket.py +++ b/web3/providers/websocket.py @@ -133,8 +133,8 @@ async def coro_make_request(self, request_data: bytes) -> RPCResponse: ) def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: - self.logger.debug("Making request WebSocket. URI: %s, " - "Method: %s", self.endpoint_uri, method) + self.logger.debug(f"Making request WebSocket. URI: {self.endpoint_uri}, " + f"Method: {method}") request_data = self.encode_rpc_request(method, params) future = asyncio.run_coroutine_threadsafe( self.coro_make_request(request_data), diff --git a/web3/tools/pytest_ethereum/linker.py b/web3/tools/pytest_ethereum/linker.py index c0804d0136..d7385ea857 100644 --- a/web3/tools/pytest_ethereum/linker.py +++ b/web3/tools/pytest_ethereum/linker.py @@ -82,7 +82,7 @@ def _deploy( manifest = insert_deployment( package, contract_name, deployment_data, latest_block_uri ) - logger.info("%s deployed." % contract_name) + logger.info(f"{contract_name} deployed.") return Package(manifest, package.w3) @@ -107,8 +107,7 @@ def link(contract: ContractName, linked_type: str, package: Package) -> Package: to_hex(linked_factory.bytecode), ) logger.info( - "%s linked to %s at address %s." - % (contract, linked_type, to_checksum_address(deployment_address)) + f"{contract} linked to {linked_type} at address {to_checksum_address(deployment_address)}." ) return Package(manifest, package.w3) @@ -120,5 +119,5 @@ def run_python(callback_fn: Callable[..., None], package: Package) -> Package: the contracts in the package. """ callback_fn(package) - logger.info("%s python function ran." % callback_fn.__name__) + logger.info(f"{callback_fn.__name__} python function ran.") return package