From d8497354a855a50a0a8caab93181c30a6901d595 Mon Sep 17 00:00:00 2001 From: Harmouch101 Date: Tue, 8 Mar 2022 18:43:51 +0200 Subject: [PATCH] :zap: update! Signed-off-by: Harmouch101 --- docs/v4_migration.rst | 4 +- docs/web3.eth.rst | 4 +- ethpm/contract.py | 12 ++--- ethpm/tools/builder.py | 2 +- ethpm/validation/manifest.py | 12 ++--- .../contracts/test_contract_call_interface.py | 6 +-- ...st_contract_method_to_argument_matching.py | 6 +-- .../test_filter_against_transaction_logs.py | 12 ++--- .../middleware/test_fixture_middleware.py | 5 +- .../test_simple_cache_middleware.py | 2 +- .../test_time_based_cache_middleware.py | 2 +- .../middleware/test_transaction_signing.py | 5 +- tests/core/providers/test_ipc_provider.py | 2 +- .../core/providers/test_websocket_provider.py | 4 +- .../test_abi_filtering_by_argument_name.py | 14 ++--- tests/ethpm/_utils/test_contract_utils.py | 10 ++-- tests/ethpm/validation/test_manifest.py | 8 +-- tests/integration/generate_fixtures/common.py | 14 +++-- .../generate_fixtures/go_ethereum.py | 7 +-- tests/integration/go_ethereum/conftest.py | 7 +-- .../go_ethereum/test_goethereum_http.py | 2 +- .../go_ethereum/test_goethereum_ws.py | 2 +- web3/_utils/abi.py | 52 ++++++++----------- web3/_utils/async_transactions.py | 4 +- web3/_utils/blocks.py | 3 +- web3/_utils/caching.py | 8 +-- web3/_utils/contracts.py | 25 ++++----- web3/_utils/datatypes.py | 6 +-- web3/_utils/encoding.py | 20 ++++--- web3/_utils/events.py | 10 ++-- web3/_utils/filters.py | 2 +- web3/_utils/http.py | 5 +- web3/_utils/math.py | 5 +- .../go_ethereum_admin_module.py | 2 +- web3/_utils/rpc_abi.py | 2 +- web3/_utils/threads.py | 2 +- web3/_utils/transactions.py | 6 +-- web3/_utils/validation.py | 17 +++--- web3/contract.py | 23 ++++---- web3/main.py | 2 +- web3/manager.py | 2 +- web3/middleware/filter.py | 8 +-- web3/middleware/signing.py | 2 +- web3/middleware/stalecheck.py | 4 +- web3/providers/async_rpc.py | 2 +- web3/providers/auto.py | 7 ++- web3/providers/eth_tester/defaults.py | 8 ++- web3/providers/ipc.py | 8 +-- web3/providers/rpc.py | 2 +- web3/providers/websocket.py | 8 +-- web3/tools/benchmark/node.py | 2 +- 51 files changed, 180 insertions(+), 209 deletions(-) diff --git a/docs/v4_migration.rst b/docs/v4_migration.rst index 14ca20f2e1..f7c2a4ceed 100644 --- a/docs/v4_migration.rst +++ b/docs/v4_migration.rst @@ -68,7 +68,7 @@ printing out new block hashes as they appear: .. code-block:: python >>> def new_block_callback(block_hash): - ... print "New Block: {0}".format(block_hash) + ... print(f"New Block: {block_hash}") ... >>> new_block_filter = web3.eth.filter('latest') >>> new_block_filter.watch(new_block_callback) @@ -79,7 +79,7 @@ In v4, that same logic: >>> new_block_filter = web3.eth.filter('latest') >>> for block_hash in new_block_filter.get_new_entries(): - ... print("New Block: {}".format(block_hash)) + ... print(f"New Block: {block_hash}") The caller is responsible for polling the results from ``get_new_entries()``. See :ref:`asynchronous_filters` for examples of filter-event handling with web3 v4. diff --git a/docs/web3.eth.rst b/docs/web3.eth.rst index eaa1653782..9fbe9c13ab 100644 --- a/docs/web3.eth.rst +++ b/docs/web3.eth.rst @@ -364,7 +364,7 @@ The following methods are available on the ``web3.eth`` namespace. assert rlp_account == HexaryTrie.get_from_proof( root, trie_key, format_proof_nodes(proof.accountProof) - ), "Failed to verify account proof {}".format(proof.address) + ), f"Failed to verify account proof {proof.address}" for storage_proof in proof.storageProof: trie_key = keccak(pad_bytes(b'\x00', 32, storage_proof.key)) @@ -376,7 +376,7 @@ The following methods are available on the ``web3.eth`` namespace. assert rlp_value == HexaryTrie.get_from_proof( root, trie_key, format_proof_nodes(storage_proof.proof) - ), "Failed to verify storage proof {}".format(storage_proof.key) + ), f"Failed to verify storage proof {storage_proof.key}" return True diff --git a/ethpm/contract.py b/ethpm/contract.py index d9b226d392..e56d6670c9 100644 --- a/ethpm/contract.py +++ b/ethpm/contract.py @@ -56,7 +56,7 @@ def __init__(self, address: bytes, **kwargs: Any) -> None: ) validate_address(address) # type ignored to allow for undefined **kwargs on `Contract` base class __init__ - super(LinkableContract, self).__init__(address=address, **kwargs) # type: ignore + super().__init__(address=address, **kwargs) # type: ignore @classmethod def factory( @@ -69,7 +69,7 @@ def factory( if not is_prelinked_bytecode(to_bytes(hexstr=bytecode), dep_link_refs): needs_bytecode_linking = True kwargs = assoc(kwargs, "needs_bytecode_linking", needs_bytecode_linking) - return super(LinkableContract, cls).factory(w3, class_name, **kwargs) + return super().factory(w3, class_name, **kwargs) @classmethod def constructor(cls, *args: Any, **kwargs: Any) -> ContractConstructor: @@ -77,7 +77,7 @@ def constructor(cls, *args: Any, **kwargs: Any) -> ContractConstructor: raise BytecodeLinkingError( "Contract cannot be deployed until its bytecode is linked." ) - return super(LinkableContract, cls).constructor(*args, **kwargs) + return super().constructor(*args, **kwargs) @classmethod def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]: @@ -111,7 +111,7 @@ def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None: """ Validates that ContractType keys in attr_dict reference existing manifest ContractTypes. """ - attr_dict_names = list(attr_dict.keys()) + attr_dict_names = attr_dict.keys() if not self.unlinked_references and not self.linked_references: raise BytecodeLinkingError( @@ -122,8 +122,8 @@ def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None: linked_refs = self.linked_references or ({},) all_link_refs = unlinked_refs + linked_refs - all_link_names = [ref["name"] for ref in all_link_refs if ref] - if set(attr_dict_names) != set(all_link_names): + all_link_names = {ref["name"] for ref in all_link_refs if ref} + if attr_dict_names != all_link_names: raise BytecodeLinkingError( "All link references must be defined when calling " "`link_bytecode` on a contract factory." diff --git a/ethpm/tools/builder.py b/ethpm/tools/builder.py index 895b790c09..6f38968402 100644 --- a/ethpm/tools/builder.py +++ b/ethpm/tools/builder.py @@ -498,7 +498,7 @@ def normalize_compiler_output(compiler_output: Dict[str, Any]) -> Dict[str, Any] ] paths, names = zip(*paths_and_names) if len(names) != len(set(names)): - duplicates = set([name for name in names if names.count(name) > 1]) + duplicates = {name for name in names if names.count(name) > 1} raise ManifestBuildingError( f"Duplicate contract types: {duplicates} were found in the compiler output." ) diff --git a/ethpm/validation/manifest.py b/ethpm/validation/manifest.py index 6aba1b1034..eb94f86523 100644 --- a/ethpm/validation/manifest.py +++ b/ethpm/validation/manifest.py @@ -66,11 +66,11 @@ def _load_schema_data() -> Dict[str, Any]: def extract_contract_types_from_deployments(deployment_data: List[Any]) -> Set[str]: - contract_types = set( + contract_types = { deployment["contractType"] for chain_deployments in deployment_data for deployment in chain_deployments.values() - ) + } return contract_types @@ -108,11 +108,11 @@ def validate_manifest_deployments(manifest: Dict[str, Any]) -> None: """ Validate that a manifest's deployments contracts reference existing contractTypes. """ - if set(("contractTypes", "deployments")).issubset(manifest): - all_contract_types = list(manifest["contractTypes"].keys()) - all_deployments = list(manifest["deployments"].values()) + if {"contractTypes", "deployments"}.issubset(manifest): + all_contract_types = manifest["contractTypes"].keys() + all_deployments = manifest["deployments"].values() all_deployment_names = extract_contract_types_from_deployments(all_deployments) - missing_contract_types = set(all_deployment_names).difference( + missing_contract_types = all_deployment_names.difference( all_contract_types ) if missing_contract_types: diff --git a/tests/core/contracts/test_contract_call_interface.py b/tests/core/contracts/test_contract_call_interface.py index 4e67c7d1cd..34a754191c 100644 --- a/tests/core/contracts/test_contract_call_interface.py +++ b/tests/core/contracts/test_contract_call_interface.py @@ -602,9 +602,9 @@ def test_returns_data_from_specified_block(w3, math_contract): message_regex = ( r"\nCould not identify the intended function with name `.*`, " - r"positional argument\(s\) of type `.*` and " - r"keyword argument\(s\) of type `.*`." - r"\nFound .* function\(s\) with the name `.*`: .*" + r"positional arguments? of type `.*` and " + r"keyword arguments? of type `.*`." + r"\nFound .* functions? with the name `.*`: .*" ) diagnosis_arg_regex = ( r"\nFunction invocation failed due to improper number of arguments." diff --git a/tests/core/contracts/test_contract_method_to_argument_matching.py b/tests/core/contracts/test_contract_method_to_argument_matching.py index 8f80dbf6c6..d4c051b2a0 100644 --- a/tests/core/contracts/test_contract_method_to_argument_matching.py +++ b/tests/core/contracts/test_contract_method_to_argument_matching.py @@ -150,7 +150,7 @@ def test_finds_function_with_matching_args(w3, arguments, expected_types): abi = Contract._find_matching_fn_abi('a', arguments) assert abi['name'] == 'a' assert len(abi['inputs']) == len(expected_types) - assert set(get_abi_input_types(abi)) == set(expected_types) + assert get_abi_input_types(abi) == expected_types def test_finds_function_with_matching_args_deprecation_warning(w3): @@ -160,7 +160,7 @@ def test_finds_function_with_matching_args_deprecation_warning(w3): abi = Contract._find_matching_fn_abi('a', ['']) assert abi['name'] == 'a' assert len(abi['inputs']) == len(['bytes32']) - assert set(get_abi_input_types(abi)) == set(['bytes32']) + assert get_abi_input_types(abi) == ['bytes32'] def test_error_when_duplicate_match(w3): @@ -193,4 +193,4 @@ def test_strict_finds_function_with_matching_args(w3_strict_abi, arguments, expe abi = Contract._find_matching_fn_abi('a', arguments) assert abi['name'] == 'a' assert len(abi['inputs']) == len(expected_types) - assert set(get_abi_input_types(abi)) == set(expected_types) + assert get_abi_input_types(abi) == expected_types diff --git a/tests/core/filtering/test_filter_against_transaction_logs.py b/tests/core/filtering/test_filter_against_transaction_logs.py index 664ec64b95..d1e63a4e43 100644 --- a/tests/core/filtering/test_filter_against_transaction_logs.py +++ b/tests/core/filtering/test_filter_against_transaction_logs.py @@ -22,8 +22,8 @@ def test_sync_filter_against_log_events(w3_empty, txn_filter = w3.eth.filter({}) - txn_hashes = [] - txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) + txn_hashes = set() + txn_hashes.add(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) for txn_hash in txn_hashes: wait_for_transaction(w3, txn_hash) @@ -34,7 +34,7 @@ def test_sync_filter_against_log_events(w3_empty, seen_logs = txn_filter.get_new_entries() - assert set(txn_hashes) == set(log['transactionHash'] for log in seen_logs) + assert txn_hashes == {log['transactionHash'] for log in seen_logs} @pytest.mark.skip(reason="fixture 'w3_empty' not found") @@ -51,9 +51,9 @@ def test_async_filter_against_log_events(w3_empty, txn_filter = w3.eth.filter({}) txn_filter.watch(seen_logs.append) - txn_hashes = [] + txn_hashes = set() - txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) + txn_hashes.add(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact()) for txn_hash in txn_hashes: wait_for_transaction(w3, txn_hash) @@ -64,4 +64,4 @@ def test_async_filter_against_log_events(w3_empty, txn_filter.stop_watching(30) - assert set(txn_hashes) == set(log['transactionHash'] for log in seen_logs) + assert txn_hashes == {log['transactionHash'] for log in seen_logs} diff --git a/tests/core/middleware/test_fixture_middleware.py b/tests/core/middleware/test_fixture_middleware.py index 19ed3816c4..1cb9eb9b7b 100644 --- a/tests/core/middleware/test_fixture_middleware.py +++ b/tests/core/middleware/test_fixture_middleware.py @@ -13,10 +13,7 @@ class DummyProvider(BaseProvider): def make_request(self, method, params): - raise NotImplementedError("Cannot make request for {0}:{1}".format( - method, - params, - )) + raise NotImplementedError(f"Cannot make request for {method}:{params}") @pytest.fixture diff --git a/tests/core/middleware/test_simple_cache_middleware.py b/tests/core/middleware/test_simple_cache_middleware.py index 2f09a10ff9..3cbe96e761 100644 --- a/tests/core/middleware/test_simple_cache_middleware.py +++ b/tests/core/middleware/test_simple_cache_middleware.py @@ -87,7 +87,7 @@ def result_cb(method, params): def test_simple_cache_middleware_does_not_cache_error_responses(w3_base): w3 = w3_base w3.middleware_onion.add(construct_error_generator_middleware({ - 'fake_endpoint': lambda *_: 'msg-{0}'.format(str(uuid.uuid4())), + 'fake_endpoint': lambda *_: f'msg-{uuid.uuid4()}', })) w3.middleware_onion.add(construct_simple_cache_middleware( diff --git a/tests/core/middleware/test_time_based_cache_middleware.py b/tests/core/middleware/test_time_based_cache_middleware.py index 968160171f..d2ee1a9502 100644 --- a/tests/core/middleware/test_time_based_cache_middleware.py +++ b/tests/core/middleware/test_time_based_cache_middleware.py @@ -130,7 +130,7 @@ def test_time_based_cache_middleware_does_not_cache_error_response( counter = itertools.count() def mk_error(method, params): - return "error-number-{0}".format(next(counter)) + return f"error-number-{next(counter)}" w3.middleware_onion.add(construct_error_generator_middleware({ 'fake_endpoint': mk_error, diff --git a/tests/core/middleware/test_transaction_signing.py b/tests/core/middleware/test_transaction_signing.py index bb9d2a7dbb..8d1ccefec8 100644 --- a/tests/core/middleware/test_transaction_signing.py +++ b/tests/core/middleware/test_transaction_signing.py @@ -83,10 +83,7 @@ class DummyProvider(BaseProvider): def make_request(self, method, params): - raise NotImplementedError("Cannot make request for {0}:{1}".format( - method, - params, - )) + raise NotImplementedError(f"Cannot make request for {method}:{params}") @pytest.fixture() diff --git a/tests/core/providers/test_ipc_provider.py b/tests/core/providers/test_ipc_provider.py index 2b1042b007..5f856eed7a 100644 --- a/tests/core/providers/test_ipc_provider.py +++ b/tests/core/providers/test_ipc_provider.py @@ -23,7 +23,7 @@ @pytest.fixture def jsonrpc_ipc_pipe_path(): with tempfile.TemporaryDirectory() as temp_dir: - ipc_path = os.path.join(temp_dir, '{0}.ipc'.format(uuid.uuid4())) + ipc_path = os.path.join(temp_dir, f'{uuid.uuid4()}.ipc') try: yield ipc_path finally: diff --git a/tests/core/providers/test_websocket_provider.py b/tests/core/providers/test_websocket_provider.py index 0cf475d31e..25037b1fa0 100644 --- a/tests/core/providers/test_websocket_provider.py +++ b/tests/core/providers/test_websocket_provider.py @@ -55,7 +55,7 @@ async def empty_server(websocket, path): def w3(open_port, start_websocket_server): # need new event loop as the one used by server is already running event_loop = asyncio.new_event_loop() - endpoint_uri = 'ws://127.0.0.1:{}'.format(open_port) + endpoint_uri = f'ws://127.0.0.1:{open_port}' event_loop.run_until_complete(wait_for_ws(endpoint_uri)) provider = WebsocketProvider(endpoint_uri, websocket_timeout=0.01) return Web3(provider) @@ -68,6 +68,6 @@ def test_websocket_provider_timeout(w3): def test_restricted_websocket_kwargs(): invalid_kwargs = {'uri': 'ws://127.0.0.1:8546'} - re_exc_message = r'.*found: {0}*'.format(set(invalid_kwargs.keys())) + re_exc_message = f'.*found: {set(invalid_kwargs)!r}*' with pytest.raises(ValidationError, match=re_exc_message): WebsocketProvider(websocket_kwargs=invalid_kwargs) diff --git a/tests/core/utilities/test_abi_filtering_by_argument_name.py b/tests/core/utilities/test_abi_filtering_by_argument_name.py index 2baac9e355..a9687fb50f 100644 --- a/tests/core/utilities/test_abi_filtering_by_argument_name.py +++ b/tests/core/utilities/test_abi_filtering_by_argument_name.py @@ -48,14 +48,14 @@ @pytest.mark.parametrize( 'argument_names,expected', ( - ([], ['func_1', 'func_2', 'func_3', 'func_4']), - (['a'], ['func_2', 'func_3', 'func_4']), - (['a', 'c'], ['func_4']), - (['c'], ['func_4']), - (['b'], ['func_3', 'func_4']), + ([], {'func_1', 'func_2', 'func_3', 'func_4'}), + (['a'], {'func_2', 'func_3', 'func_4'}), + (['a', 'c'], {'func_4'}), + (['c'], {'func_4'}), + (['b'], {'func_3', 'func_4'}), ) ) def test_filter_by_arguments_1(argument_names, expected): actual_matches = filter_by_argument_name(argument_names, ABI) - function_names = [match['name'] for match in actual_matches] - assert set(function_names) == set(expected) + function_names = {match['name'] for match in actual_matches} + assert function_names == expected diff --git a/tests/ethpm/_utils/test_contract_utils.py b/tests/ethpm/_utils/test_contract_utils.py index 1ffd417901..a6bd9f00e2 100644 --- a/tests/ethpm/_utils/test_contract_utils.py +++ b/tests/ethpm/_utils/test_contract_utils.py @@ -58,11 +58,11 @@ def test_validate_contract_name_invalidates(name): @pytest.mark.parametrize( "contract_data,expected_kwargs", ( - ({"abi": ""}, ["abi"]), - ({"deploymentBytecode": {"bytecode": ""}}, ["bytecode"]), + ({"abi": ""}, {"abi"}), + ({"deploymentBytecode": {"bytecode": ""}}, {"bytecode"}), ( {"abi": "", "runtimeBytecode": {"bytecode": ""}}, - ["abi", "bytecode_runtime"], + {"abi", "bytecode_runtime"}, ), ( { @@ -74,13 +74,13 @@ def test_validate_contract_name_invalidates(name): ], }, }, - ["abi", "bytecode", "unlinked_references"], + {"abi", "bytecode", "unlinked_references"}, ), ), ) def test_generate_contract_factory_kwargs(contract_data, expected_kwargs): contract_factory = generate_contract_factory_kwargs(contract_data) - assert set(contract_factory.keys()) == set(expected_kwargs) + assert contract_factory.keys() == expected_kwargs def test_validate_w3_instance_validates(w3): diff --git a/tests/ethpm/validation/test_manifest.py b/tests/ethpm/validation/test_manifest.py index c68089f7cc..348e2ff388 100644 --- a/tests/ethpm/validation/test_manifest.py +++ b/tests/ethpm/validation/test_manifest.py @@ -78,17 +78,17 @@ def test_validate_deployments_without_deployment(manifest_with_no_deployments): @pytest.mark.parametrize( "data,expected", ( - ({}, set()), - ([{"some": {"contractType": "one"}}], set(["one"])), + ([], {}), + ([{"some": {"contractType": "one"}}], {"one"}), ( [{"some": {"contractType": "one"}, "other": {"contractType": "two"}}], - set(["one", "two"]), + {"one", "two"}, ), ), ) def test_extract_contract_types_from_deployments(data, expected): actual = extract_contract_types_from_deployments(data) - assert actual == expected + assert actual == set(expected) def test_validate_manifest_version_validates_version_three_string(): diff --git a/tests/integration/generate_fixtures/common.py b/tests/integration/generate_fixtures/common.py index d7d20a8964..a6bc487e6b 100644 --- a/tests/integration/generate_fixtures/common.py +++ b/tests/integration/generate_fixtures/common.py @@ -183,11 +183,8 @@ def get_geth_process(geth_binary, output, errors = proc.communicate() print( "Geth Process Exited:\n" - "stdout:{0}\n\n" - "stderr:{1}\n\n".format( - to_text(output), - to_text(errors), - ) + f"stdout:{to_text(output)}\n\n" + f"stderr:{to_text(errors)}\n\n" ) @@ -235,12 +232,13 @@ def mine_transaction_hash(w3, txn_hash): def deploy_contract(w3, name, factory): + name = name.upper() w3.geth.personal.unlock_account(w3.eth.coinbase, KEYFILE_PW) deploy_txn_hash = factory.constructor().transact({'from': w3.eth.coinbase}) - print('{0}_CONTRACT_DEPLOY_HASH: '.format(name.upper()), deploy_txn_hash) + print(f'{name}_CONTRACT_DEPLOY_HASH: {deploy_txn_hash}') deploy_receipt = mine_transaction_hash(w3, deploy_txn_hash) - print('{0}_CONTRACT_DEPLOY_TRANSACTION_MINED'.format(name.upper())) + print(f'{name}_CONTRACT_DEPLOY_TRANSACTION_MINED') contract_address = deploy_receipt['contractAddress'] assert is_checksum_address(contract_address) - print('{0}_CONTRACT_ADDRESS:'.format(name.upper()), contract_address) + print(f'{name}_CONTRACT_ADDRESS: {contract_address}') return deploy_receipt diff --git a/tests/integration/generate_fixtures/go_ethereum.py b/tests/integration/generate_fixtures/go_ethereum.py index d6d55b7ee2..eadbfb00bc 100644 --- a/tests/integration/generate_fixtures/go_ethereum.py +++ b/tests/integration/generate_fixtures/go_ethereum.py @@ -91,11 +91,8 @@ def get_geth_process(geth_binary, print( "Geth Process Exited:\n" - "stdout:{0}\n\n" - "stderr:{1}\n\n".format( - to_text(output), - to_text(errors), - ) + f"stdout:{to_text(output)}\n\n" + f"stderr:{to_text(errors)}\n\n" ) diff --git a/tests/integration/go_ethereum/conftest.py b/tests/integration/go_ethereum/conftest.py index 0862c47aa1..622e11f106 100644 --- a/tests/integration/go_ethereum/conftest.py +++ b/tests/integration/go_ethereum/conftest.py @@ -121,11 +121,8 @@ def geth_process(geth_binary, datadir, genesis_file, geth_command_arguments): output, errors = proc.communicate() print( "Geth Process Exited:\n" - "stdout:{0}\n\n" - "stderr:{1}\n\n".format( - to_text(output), - to_text(errors), - ) + f"stdout:{to_text(output)}\n\n" + f"stderr:{to_text(errors)}\n\n" ) diff --git a/tests/integration/go_ethereum/test_goethereum_http.py b/tests/integration/go_ethereum/test_goethereum_http.py index 53a624faad..ec209d02e1 100644 --- a/tests/integration/go_ethereum/test_goethereum_http.py +++ b/tests/integration/go_ethereum/test_goethereum_http.py @@ -58,7 +58,7 @@ def rpc_port(): @pytest.fixture(scope="module") def endpoint_uri(rpc_port): - return 'http://localhost:{0}'.format(rpc_port) + return f'http://localhost:{rpc_port}' def _geth_command_arguments(rpc_port, diff --git a/tests/integration/go_ethereum/test_goethereum_ws.py b/tests/integration/go_ethereum/test_goethereum_ws.py index 647681ede8..22367aa570 100644 --- a/tests/integration/go_ethereum/test_goethereum_ws.py +++ b/tests/integration/go_ethereum/test_goethereum_ws.py @@ -27,7 +27,7 @@ def ws_port(): @pytest.fixture(scope="module") def endpoint_uri(ws_port): - return 'ws://localhost:{0}'.format(ws_port) + return f'ws://localhost:{ws_port}' def _geth_command_arguments(ws_port, diff --git a/web3/_utils/abi.py b/web3/_utils/abi.py index 698f4151cd..aef5c6c137 100644 --- a/web3/_utils/abi.py +++ b/web3/_utils/abi.py @@ -290,9 +290,8 @@ def validate(self) -> None: if self.value_bit_size % 8 != 0: raise ValueError( - "Invalid value bit size: {0}. Must be a multiple of 8".format( - self.value_bit_size, - ) + f"Invalid value bit size: {self.value_bit_size}. " + "Must be a multiple of 8" ) if self.value_bit_size > self.data_byte_size * 8: @@ -328,13 +327,13 @@ def validate_value(self, value: Any) -> bytes: # type: ignore self.invalidate_value( value, exc=ValueOutOfBounds, - msg="exceeds total byte size for bytes{} encoding".format(byte_size), + msg=f"exceeds total byte size for bytes{byte_size} encoding", ) elif len(value) < byte_size: self.invalidate_value( value, exc=ValueOutOfBounds, - msg="less than total byte size for bytes{} encoding".format(byte_size), + msg=f"less than total byte size for bytes{byte_size} encoding", ) return value @@ -438,10 +437,8 @@ def merge_args_and_kwargs( # Ensure the function is being applied to the correct number of args if len(args) + len(kwargs) != len(function_abi.get('inputs', [])): raise TypeError( - "Incorrect argument count. Expected '{0}'. Got '{1}'".format( - len(function_abi['inputs']), - len(args) + len(kwargs), - ) + f"Incorrect argument count. Expected '{len(function_abi['inputs'])}" + f". Got '{len(args) + len(kwargs)}'" ) # If no keyword args were given, we don't need to align them @@ -456,10 +453,9 @@ def merge_args_and_kwargs( duplicate_args = kwarg_names.intersection(args_as_kwargs.keys()) if duplicate_args: raise TypeError( - "{fn_name}() got multiple values for argument(s) '{dups}'".format( - fn_name=function_abi['name'], - dups=', '.join(duplicate_args), - ) + f"{function_abi.get('name')}() got multiple values for " + f"argument{'s' if len(duplicate_args) > 1 else ''} " + f"'{', '.join(duplicate_args)}'" ) # Check for unknown args @@ -467,16 +463,14 @@ def merge_args_and_kwargs( if unknown_args: if function_abi.get('name'): raise TypeError( - "{fn_name}() got unexpected keyword argument(s) '{dups}'".format( - fn_name=function_abi.get('name'), - dups=', '.join(unknown_args), - ) + f"{function_abi.get('name')}() got unexpected keyword argument" + f"{'s' if len(unknown_args) > 1 else ''} " + f"{', '.join(unknown_args)}'" ) raise TypeError( - "Type: '{_type}' got unexpected keyword argument(s) '{dups}'".format( - _type=function_abi.get('type'), - dups=', '.join(unknown_args), - ) + f"Type: '{function_abi.get('type')}' got unexpected keyword " + f"argument{'s' if len(unknown_args) > 1 else ''} " + f"{', '.join(unknown_args)}'" ) # Sort args according to their position in the ABI and unzip them from their @@ -545,10 +539,8 @@ def _align_abi_input(arg_abi: ABIFunctionParams, arg: Any) -> Tuple[Any, ...]: if not is_list_like(aligned_arg): raise TypeError( - 'Expected non-string sequence for "{}" component type: got {}'.format( - arg_abi['type'], - aligned_arg, - ), + f'Expected non-string sequence for "{arg_abi.get("type")}" ' + f'component type: got {aligned_arg}' ) # convert NamedTuple to regular tuple @@ -604,9 +596,9 @@ def get_constructor_abi(contract_abi: ABI) -> ABIFunction: INT_SIZES = range(8, 257, 8) BYTES_SIZES = range(1, 33) -UINT_TYPES = ['uint{0}'.format(i) for i in INT_SIZES] -INT_TYPES = ['int{0}'.format(i) for i in INT_SIZES] -BYTES_TYPES = ['bytes{0}'.format(i) for i in BYTES_SIZES] + ['bytes32.byte'] +UINT_TYPES = [f'uint{i}' for i in INT_SIZES] +INT_TYPES = [f'int{i}' for i in INT_SIZES] +BYTES_TYPES = [f'bytes{i}' for i in BYTES_SIZES] + ['bytes32.byte'] STATIC_TYPES = list(itertools.chain( ['address', 'bool'], @@ -694,7 +686,7 @@ def size_of_type(abi_type: TypeStr) -> int: def sub_type_of_array_type(abi_type: TypeStr) -> str: if not is_array_type(abi_type): raise ValueError( - "Cannot parse subtype of nonarray abi-type: {0}".format(abi_type) + f"Cannot parse subtype of nonarray abi-type: {abi_type}" ) return re.sub(END_BRACKETS_OF_ARRAY_TYPE_REGEX, '', abi_type, 1) @@ -703,7 +695,7 @@ def sub_type_of_array_type(abi_type: TypeStr) -> str: def length_of_array_type(abi_type: TypeStr) -> int: if not is_array_type(abi_type): raise ValueError( - "Cannot parse length of nonarray abi-type: {0}".format(abi_type) + f"Cannot parse length of nonarray abi-type: {abi_type}" ) inner_brackets = re.search(END_BRACKETS_OF_ARRAY_TYPE_REGEX, abi_type).group(0).strip("[]") diff --git a/web3/_utils/async_transactions.py b/web3/_utils/async_transactions.py index 116fdf8898..7e6153e047 100644 --- a/web3/_utils/async_transactions.py +++ b/web3/_utils/async_transactions.py @@ -35,8 +35,8 @@ async def get_buffered_gas_estimate( if gas_estimate > gas_limit: raise ValueError( "Contract does not appear to be deployable within the " - "current network gas limits. Estimated: {0}. Current gas " - "limit: {1}".format(gas_estimate, gas_limit) + f"current network gas limits. Estimated: {gas_estimate}. " + f"Current gas limit: {gas_limit}" ) return min(gas_limit, gas_estimate + gas_buffer) diff --git a/web3/_utils/blocks.py b/web3/_utils/blocks.py index 63ff37328c..d05e33c38e 100644 --- a/web3/_utils/blocks.py +++ b/web3/_utils/blocks.py @@ -70,5 +70,6 @@ def select_method_for_block_identifier( return if_number else: raise ValueError( - "Value did not match any of the recognized block identifiers: {0}".format(value) + "Value did not match any of the recognized block identifiers: " + f"{value}" ) diff --git a/web3/_utils/caching.py b/web3/_utils/caching.py index 09cdf25335..ce11235312 100644 --- a/web3/_utils/caching.py +++ b/web3/_utils/caching.py @@ -39,7 +39,7 @@ def generate_cache_key(value: Any) -> str: in value ))) else: - raise TypeError("Cannot generate cache key for value {0} of type {1}".format( - value, - type(value), - )) + raise TypeError( + f"Cannot generate cache key for value {value} of type " + f"{type(value)}" + ) diff --git a/web3/_utils/contracts.py b/web3/_utils/contracts.py index 97a0b1d17c..fbddcf7768 100644 --- a/web3/_utils/contracts.py +++ b/web3/_utils/contracts.py @@ -146,18 +146,15 @@ def find_matching_fn_abi( ) message = ( - "\nCould not identify the intended function with name `{name}`, " - "positional argument(s) of type `{arg_types}` and " - "keyword argument(s) of type `{kwarg_types}`." - "\nFound {num_candidates} function(s) with the name `{name}`: {candidates}" - "{diagnosis}" - ).format( - name=fn_identifier, - arg_types=tuple(map(type, args)), - kwarg_types=valmap(type, kwargs), - num_candidates=len(matching_identifiers), - candidates=matching_function_signatures, - diagnosis=diagnosis, + f"\nCould not identify the intended function with name `" + f"{fn_identifier}`, positional argument" + f"{'s' if len(args) > 1 else ''} of type " + f"`{tuple(map(type, args))}` and keyword argument" + f"{'s' if len(kwargs) > 1 else ''} of type " + f"`{valmap(type, kwargs)}`.\nFound {len(matching_identifiers)} " + f"function{'s' if len(matching_identifiers) > 1 else ''} with " + f"the name `{fn_identifier}`" + f": {matching_function_signatures}{diagnosis}" ) raise ValidationError(message) @@ -171,9 +168,7 @@ def encode_abi( if not check_if_arguments_can_be_encoded(abi, w3.codec, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " - "ABI type. Expected types are: {0}".format( - ', '.join(argument_types), - ) + f"ABI type. Expected types are: {', '.join(argument_types)}" ) normalizers = [ diff --git a/web3/_utils/datatypes.py b/web3/_utils/datatypes.py index 957de2a22e..110449fd75 100644 --- a/web3/_utils/datatypes.py +++ b/web3/_utils/datatypes.py @@ -18,9 +18,9 @@ def verify_attr(class_name: str, key: str, namespace: Collection[str]) -> None: if key not in namespace: raise AttributeError( - "Property {0} not found on {1} class. " - "`{1}.factory` only accepts keyword arguments which are " - "present on the {1} class".format(key, class_name) + f"Property {key} not found on {class_name} class. " + f"`{class_name}.factory` only accepts keyword arguments which are " + f"present on the {class_name} class" ) diff --git a/web3/_utils/encoding.py b/web3/_utils/encoding.py index 5b9a4a4a56..7482db29fa 100644 --- a/web3/_utils/encoding.py +++ b/web3/_utils/encoding.py @@ -88,7 +88,7 @@ def hex_encode_abi_type(abi_type: TypeStr, value: Any, return to_hex(text=value) else: raise ValueError( - "Unsupported ABI type: {0}".format(abi_type) + f"Unsupported ABI type: {abi_type}" ) @@ -169,9 +169,8 @@ def hexstr_if_str( (primitive, hexstr) = (None, hexstr_or_primitive) if remove_0x_prefix(HexStr(hexstr)) and not is_hex(hexstr): raise ValueError( - "when sending a str, it must be a hex string. Got: {0!r}".format( - hexstr_or_primitive, - ) + "when sending a str, it must be a hex string. Got: " + f"{hexstr_or_primitive!r}" ) else: (primitive, hexstr) = (hexstr_or_primitive, None) @@ -208,10 +207,15 @@ def _friendly_json_encode(self, obj: Dict[Any, Any], except TypeError as full_exception: if hasattr(obj, 'items'): item_errors = '; '.join(self._json_mapping_errors(obj)) - raise TypeError("dict had unencodable value at keys: {{{}}}".format(item_errors)) + raise TypeError( + "dict had unencodable value at keys: " + f"{{{item_errors}}}" + ) elif is_list_like(obj): element_errors = '; '.join(self._json_list_errors(obj)) - raise TypeError("list had unencodable value at index: [{}]".format(element_errors)) + raise TypeError( + f"list had unencodable value at index: [{element_errors}]" + ) else: raise full_exception @@ -220,7 +224,7 @@ def json_decode(self, json_str: str) -> Dict[Any, Any]: decoded = json.loads(json_str) return decoded except json.decoder.JSONDecodeError as exc: - err_msg = 'Could not decode {} because of {}.'.format(repr(json_str), exc) + err_msg = f'Could not decode {json_str!r} because of {exc}.' # Calling code may rely on catching JSONDecodeError to recognize bad json # so we have to re-raise the same type. raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos) @@ -230,7 +234,7 @@ def json_encode(self, obj: Dict[Any, Any], try: return self._friendly_json_encode(obj, cls=cls) except TypeError as exc: - raise TypeError("Could not encode to JSON: {}".format(exc)) + raise TypeError(f"Could not encode to JSON: {exc}") def to_4byte_hex(hex_or_str_or_bytes: Union[HexStr, str, bytes, int]) -> HexStr: diff --git a/web3/_utils/events.py b/web3/_utils/events.py index 9cfe6fb685..78bc60e94b 100644 --- a/web3/_utils/events.py +++ b/web3/_utils/events.py @@ -219,10 +219,10 @@ def get_event_data(abi_codec: ABICodec, event_abi: ABIEvent, log_entry: LogRecei log_topic_names = get_abi_input_names(ABIEvent({'inputs': log_topics_abi})) if len(log_topics) != len(log_topic_types): - raise LogTopicError("Expected {0} log topics. Got {1}".format( - len(log_topic_types), - len(log_topics), - )) + raise LogTopicError( + f"Expected {len(log_topic_types)} log topics. Got " + f"{len(log_topics)}" + ) log_data = hexstr_if_str(to_bytes, log_entry['data']) log_data_abi = exclude_indexed_event_inputs(event_abi) @@ -400,7 +400,7 @@ def filter_params(self) -> FilterParams: def deploy(self, w3: "Web3") -> "LogFilter": if not isinstance(w3, web3.Web3): - raise ValueError("Invalid web3 argument: got: {0}".format(repr(w3))) + raise ValueError(f"Invalid web3 argument: got: {w3!r}") for arg in AttributeDict.values(self.args): arg._immutable = True diff --git a/web3/_utils/filters.py b/web3/_utils/filters.py index b6a77c385f..79d3ae734f 100644 --- a/web3/_utils/filters.py +++ b/web3/_utils/filters.py @@ -97,7 +97,7 @@ def construct_event_filter_params( filter_params['address'] = [address, contract_address] else: raise ValueError( - "Unsupported type for `address` parameter: {0}".format(type(address)) + f"Unsupported type for `address` parameter: {type(address)}" ) elif address: filter_params['address'] = address diff --git a/web3/_utils/http.py b/web3/_utils/http.py index 80c7e31296..e244183877 100644 --- a/web3/_utils/http.py +++ b/web3/_utils/http.py @@ -1,8 +1,5 @@ def construct_user_agent(class_name: str) -> str: from web3 import __version__ as web3_version - user_agent = 'Web3.py/{version}/{class_name}'.format( - version=web3_version, - class_name=class_name, - ) + user_agent = f'Web3.py/{web3_version}/{class_name}' return user_agent diff --git a/web3/_utils/math.py b/web3/_utils/math.py index cb983f235b..96052bb00d 100644 --- a/web3/_utils/math.py +++ b/web3/_utils/math.py @@ -14,9 +14,10 @@ def percentile(values: Optional[Sequence[int]] = None, """ if values in [None, tuple(), []] or len(values) < 1: raise InsufficientData( - "Expected a sequence of at least 1 integers, got {0!r}".format(values)) + f"Expected a sequence of at least 1 integers, got {values!r}" + ) if percentile is None: - raise ValueError("Expected a percentile choice, got {0}".format(percentile)) + raise ValueError(f"Expected a percentile choice, got {percentile}") sorted_values = sorted(values) diff --git a/web3/_utils/module_testing/go_ethereum_admin_module.py b/web3/_utils/module_testing/go_ethereum_admin_module.py index 38505deec7..0fa20285ff 100644 --- a/web3/_utils/module_testing/go_ethereum_admin_module.py +++ b/web3/_utils/module_testing/go_ethereum_admin_module.py @@ -98,7 +98,7 @@ def test_admin_nodeInfo(self, w3: "Web3") -> None: 'protocols': AttributeDict({}) }) # Test that result gives at least the keys that are listed in `expected` - assert not set(expected.keys()).difference(result.keys()) + assert not set(expected).difference(result) class GoEthereumAsyncAdminModuleTest: diff --git a/web3/_utils/rpc_abi.py b/web3/_utils/rpc_abi.py index 641497ef42..4ebf435919 100644 --- a/web3/_utils/rpc_abi.py +++ b/web3/_utils/rpc_abi.py @@ -219,7 +219,7 @@ def apply_abi_formatters_to_dict( abi_dict: Dict[str, Any], data: Dict[Any, Any] ) -> Dict[Any, Any]: - fields = list(set(abi_dict.keys()) & set(data.keys())) + fields = list(abi_dict.keys() & data.keys()) formatted_values = map_abi_data( normalizers, [abi_dict[field] for field in fields], diff --git a/web3/_utils/threads.py b/web3/_utils/threads.py index ba45d8775e..435807dbbe 100644 --- a/web3/_utils/threads.py +++ b/web3/_utils/threads.py @@ -49,7 +49,7 @@ def __exit__( def __str__(self) -> str: if self.seconds is None: return '' - return "{0} seconds".format(self.seconds) + return f"{self.seconds} seconds" @property def expire_at(self) -> int: diff --git a/web3/_utils/transactions.py b/web3/_utils/transactions.py index 638cb89d50..40acdf0780 100644 --- a/web3/_utils/transactions.py +++ b/web3/_utils/transactions.py @@ -137,8 +137,8 @@ def get_buffered_gas_estimate( if gas_estimate > gas_limit: raise ValueError( "Contract does not appear to be deployable within the " - "current network gas limits. Estimated: {0}. Current gas " - "limit: {1}".format(gas_estimate, gas_limit) + f"current network gas limits. Estimated: {gas_estimate}. " + f"Current gas limit: {gas_limit}" ) return min(gas_limit, gas_estimate + gas_buffer) @@ -189,7 +189,7 @@ def extract_valid_transaction_params(transaction_params: TxData) -> TxParams: def assert_valid_transaction_params(transaction_params: TxParams) -> None: for param in transaction_params: if param not in VALID_TRANSACTION_PARAMS: - raise ValueError('{} is not a valid transaction parameter'.format(param)) + raise ValueError(f'{param} is not a valid transaction parameter') def prepare_replacement_transaction( diff --git a/web3/_utils/validation.py b/web3/_utils/validation.py index d59e788d61..d6080e340c 100644 --- a/web3/_utils/validation.py +++ b/web3/_utils/validation.py @@ -87,7 +87,7 @@ def validate_abi(abi: ABI) -> None: if duplicates: raise ValueError( 'Abi contains functions with colliding selectors. ' - 'Functions {0}'.format(_prepare_selector_collision_msg(duplicates)) + f'Functions {_prepare_selector_collision_msg(duplicates)}' ) @@ -96,7 +96,7 @@ def validate_abi_type(abi_type: TypeStr) -> None: Helper function for validating an abi_type """ if not is_recognized_type(abi_type): - raise ValueError("Unrecognized abi_type: {abi_type}".format(abi_type=abi_type)) + raise ValueError(f"Unrecognized abi_type: {abi_type}") def validate_abi_value(abi_type: TypeStr, value: Any) -> None: @@ -110,15 +110,13 @@ def validate_abi_value(abi_type: TypeStr, value: Any) -> None: if specified_length is not None: if specified_length < 1: raise TypeError( - "Invalid abi-type: {abi_type}. Length of fixed sized arrays" - "must be greater than 0." - .format(abi_type=abi_type) + f"Invalid abi-type: {abi_type}. Length of fixed sized " + "arrays must be greater than 0." ) if specified_length != len(value): raise TypeError( "The following array length does not the length specified" - "by the abi-type, {abi_type}: {value}" - .format(abi_type=abi_type, value=value) + f"by the abi-type, {abi_type}: {value}" ) # validate sub_types @@ -150,8 +148,7 @@ def validate_abi_value(abi_type: TypeStr, value: Any) -> None: return raise TypeError( - "The following abi value is not a '{abi_type}': {value}" - .format(abi_type=abi_type, value=value) + f"The following abi value is not a '{abi_type}': {value}" ) @@ -174,7 +171,7 @@ def validate_address(value: Any) -> None: return if not isinstance(value, str): - raise TypeError('Address {} must be provided as a string'.format(value)) + raise TypeError(f'Address {value} must be provided as a string') if not is_hex_address(value): raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value) if not is_checksum_address(value): diff --git a/web3/contract.py b/web3/contract.py index c20d0e2156..0f152ce02a 100644 --- a/web3/contract.py +++ b/web3/contract.py @@ -192,7 +192,7 @@ def __getattr__(self, function_name: str) -> "ContractFunction": ) elif function_name not in self.__dict__['_functions']: raise ABIFunctionNotFound( - "The function '{}' was not found in this contract's abi. ".format(function_name), + f"The function '{function_name}' was not found in this contract's abi. ", "Are you sure you provided the correct contract abi?" ) else: @@ -252,7 +252,7 @@ def __getattr__(self, event_name: str) -> Type['ContractEvent']: ) elif event_name not in self.__dict__['_events']: raise ABIEventFunctionNotFound( - "The event '{}' was not found in this contract's abi. ".format(event_name), + f"The event '{event_name}' was not found in this contract's abi. ", "Are you sure you provided the correct contract abi?" ) else: @@ -585,7 +585,7 @@ def _encode_constructor_data(cls, args: Optional[Any] = None, def mk_collision_prop(fn_name: str) -> Callable[[], None]: def collision_fn() -> NoReturn: - msg = "Namespace collision for function name {0} with ConciseContract API.".format(fn_name) + msg = f"Namespace collision for function name {fn_name} with ConciseContract API." raise AttributeError(msg) collision_fn.__name__ = fn_name return collision_fn @@ -687,10 +687,11 @@ def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams: def check_forbidden_keys_in_transaction( transaction: TxParams, forbidden_keys: Optional[Collection[str]] = None ) -> None: - keys_found = set(transaction.keys()) & set(forbidden_keys) + keys_found = transaction.keys() & forbidden_keys if keys_found: raise ValueError( - "Cannot set '{}' field(s) in transaction".format(', '.join(keys_found)) + f"Cannot set '{', '.join(keys_found)}'" + f"field{'s' if len(keys_found) > 1 else ''} in transaction" ) @@ -1412,12 +1413,12 @@ def __getattr__(self, function_name: str) -> Any: "The ABI for this contract contains no function definitions. ", "Are you sure you provided the correct contract ABI?" ) - elif function_name not in set(fn['name'] for fn in self._functions): + elif function_name not in {fn['name'] for fn in self._functions}: functions_available = ', '.join([fn['name'] for fn in self._functions]) raise ABIFunctionNotFound( - "The function '{}' was not found in this contract's ABI. ".format(function_name), + f"The function '{function_name}' was not found in this contract's ABI. ", "Here is a list of all of the function names found: ", - "{}. ".format(functions_available), + f"{functions_available}. ", "Did you mean to call one of those functions?" ) else: @@ -1673,11 +1674,11 @@ def get_function_by_identifier( ) -> ContractFunction: if len(fns) > 1: raise ValueError( - 'Found multiple functions with matching {0}. ' - 'Found: {1!r}'.format(identifier, fns) + f'Found multiple functions with matching {identifier}. ' + f'Found: {fns!r}' ) elif len(fns) == 0: raise ValueError( - 'Could not find any function with matching {0}'.format(identifier) + f'Could not find any function with matching {identifier}' ) return fns[0] diff --git a/web3/main.py b/web3/main.py index 5395895683..666ef18e03 100644 --- a/web3/main.py +++ b/web3/main.py @@ -314,7 +314,7 @@ def solidityKeccak(cls, abi_types: List[TypeStr], values: List[Any]) -> bytes: if len(abi_types) != len(values): raise ValueError( "Length mismatch between provided abi types and values. Got " - "{0} types and {1} values.".format(len(abi_types), len(values)) + f"{len(abi_types)} types and {len(values)} values." ) if isinstance(cls, type): diff --git a/web3/manager.py b/web3/manager.py index db5c6085b4..6cc2b68e44 100644 --- a/web3/manager.py +++ b/web3/manager.py @@ -230,7 +230,7 @@ def receive_blocking(self, request_id: UUID, timeout: Optional[float] = None) -> try: request = self.pending_requests.pop(request_id) except KeyError: - raise KeyError("Request for id:{0} not found".format(request_id)) + raise KeyError(f"Request for id:{request_id} not found") else: response = request.get(timeout=timeout) diff --git a/web3/middleware/filter.py b/web3/middleware/filter.py index 5b2f82a417..dee73d7be3 100644 --- a/web3/middleware/filter.py +++ b/web3/middleware/filter.py @@ -293,15 +293,15 @@ def get_logs(self) -> List[LogReceipt]: "fromBlock": "from_block" } -NEW_FILTER_METHODS = set([ +NEW_FILTER_METHODS = { "eth_newBlockFilter", "eth_newFilter", -]) +} -FILTER_CHANGES_METHODS = set([ +FILTER_CHANGES_METHODS = { "eth_getFilterChanges", "eth_getFilterLogs", -]) +} class RequestBlocks: diff --git a/web3/middleware/signing.py b/web3/middleware/signing.py index 4ed76a9830..b0f121f243 100644 --- a/web3/middleware/signing.py +++ b/web3/middleware/signing.py @@ -93,7 +93,7 @@ def to_account(val: Any) -> LocalAccount: "key must be one of the types: " "eth_keys.datatype.PrivateKey, eth_account.signers.local.LocalAccount, " "or raw private key as a hex string or byte string. " - "Was of type {0}".format(type(val))) + f"Was of type {type(val)}") @to_account.register(LocalAccount) diff --git a/web3/middleware/stalecheck.py b/web3/middleware/stalecheck.py index 73e8158770..e8d98188ad 100644 --- a/web3/middleware/stalecheck.py +++ b/web3/middleware/stalecheck.py @@ -20,9 +20,9 @@ if TYPE_CHECKING: from web3 import Web3 # noqa: F401 -SKIP_STALECHECK_FOR_METHODS = set([ +SKIP_STALECHECK_FOR_METHODS = { 'eth_getBlockByNumber', -]) +} def _isfresh(block: BlockData, allowable_delay: int) -> bool: diff --git a/web3/providers/async_rpc.py b/web3/providers/async_rpc.py index dc80bfdedf..04f27f3b3e 100644 --- a/web3/providers/async_rpc.py +++ b/web3/providers/async_rpc.py @@ -58,7 +58,7 @@ async def cache_async_session(self, session: ClientSession) -> None: await _cache_async_session(self.endpoint_uri, session) def __str__(self) -> str: - return "RPC connection {0}".format(self.endpoint_uri) + return f"RPC connection {self.endpoint_uri}" @to_dict def get_request_kwargs(self) -> Iterable[Tuple[str, Any]]: diff --git a/web3/providers/auto.py b/web3/providers/auto.py index 9bc49b893b..47f3f4e933 100644 --- a/web3/providers/auto.py +++ b/web3/providers/auto.py @@ -103,10 +103,9 @@ def _proxy_request(self, method: RPCEndpoint, params: Any, if provider is None: raise CannotHandleRequest( "Could not discover provider while making request: " - "method:{0}\n" - "params:{1}\n".format( - method, - params)) + f"method:{method}\n" + f"params:{params}\n" + ) return provider.make_request(method, params) diff --git a/web3/providers/eth_tester/defaults.py b/web3/providers/eth_tester/defaults.py index a33d337ef6..5c190217f8 100644 --- a/web3/providers/eth_tester/defaults.py +++ b/web3/providers/eth_tester/defaults.py @@ -102,11 +102,9 @@ def inner(*args: Any, **kwargs: Any) -> TValue: def client_version(eth_tester: "EthereumTester", params: Any) -> str: # TODO: account for the backend that is in use. from eth_tester import __version__ - return "EthereumTester/{version}/{platform}/python{v.major}.{v.minor}.{v.micro}".format( - version=__version__, - v=sys.version_info, - platform=sys.platform, - ) + v = sys.version_info + return f"EthereumTester/{__version__}/{sys.platform}/python{v.major}" \ + f".{v.minor}.{v.micro}" @curry diff --git a/web3/providers/ipc.py b/web3/providers/ipc.py index a166aabd80..1e7250451b 100644 --- a/web3/providers/ipc.py +++ b/web3/providers/ipc.py @@ -153,8 +153,8 @@ def get_default_ipc_path() -> str: # type: ignore else: raise ValueError( - "Unsupported platform '{0}'. Only darwin/linux/win32/freebsd are " - "supported. You must specify the ipc_path".format(sys.platform) + f"Unsupported platform '{sys.platform}'. Only darwin/linux/win32/" + "freebsd are supported. You must specify the ipc_path" ) @@ -202,8 +202,8 @@ def get_dev_ipc_path() -> str: # type: ignore else: raise ValueError( - "Unsupported platform '{0}'. Only darwin/linux/win32/freebsd are " - "supported. You must specify the ipc_path".format(sys.platform) + f"Unsupported platform '{sys.platform}'. Only darwin/linux/win32/" + "freebsd are supported. You must specify the ipc_path" ) diff --git a/web3/providers/rpc.py b/web3/providers/rpc.py index 74c83eac7e..13e3156aa5 100644 --- a/web3/providers/rpc.py +++ b/web3/providers/rpc.py @@ -66,7 +66,7 @@ def __init__( super().__init__() def __str__(self) -> str: - return "RPC connection {0}".format(self.endpoint_uri) + return f"RPC connection {self.endpoint_uri}" @to_dict def get_request_kwargs(self) -> Iterable[Tuple[str, Any]]: diff --git a/web3/providers/websocket.py b/web3/providers/websocket.py index ef486ff49c..0713fa830c 100644 --- a/web3/providers/websocket.py +++ b/web3/providers/websocket.py @@ -103,13 +103,13 @@ def __init__( if websocket_kwargs is None: websocket_kwargs = {} else: - found_restricted_keys = set(websocket_kwargs.keys()).intersection( + found_restricted_keys = set(websocket_kwargs).intersection( RESTRICTED_WEBSOCKET_KWARGS ) if found_restricted_keys: raise ValidationError( - '{0} are not allowed in websocket_kwargs, ' - 'found: {1}'.format(RESTRICTED_WEBSOCKET_KWARGS, found_restricted_keys) + f'{RESTRICTED_WEBSOCKET_KWARGS} are not allowed ' + f'in websocket_kwargs, found: {found_restricted_keys}' ) self.conn = PersistentWebSocket( self.endpoint_uri, websocket_kwargs @@ -117,7 +117,7 @@ def __init__( super().__init__() def __str__(self) -> str: - return "WS connection {0}".format(self.endpoint_uri) + return f"WS connection {self.endpoint_uri}" async def coro_make_request(self, request_data: bytes) -> RPCResponse: async with self.conn as conn: diff --git a/web3/tools/benchmark/node.py b/web3/tools/benchmark/node.py index 86fa3416b7..2cc23d0fe6 100644 --- a/web3/tools/benchmark/node.py +++ b/web3/tools/benchmark/node.py @@ -59,7 +59,7 @@ def _rpc_port(self) -> str: return str(port) def _endpoint_uri(self) -> str: - return "http://localhost:{0}".format(self.rpc_port) + return f"http://localhost:{self.rpc_port}" def _geth_binary(self) -> str: if "GETH_BINARY" in os.environ: