Skip to content

Commit

Permalink
🧹 clean python2 syntax.
Browse files Browse the repository at this point in the history
Signed-off-by: Harmouch101 <[email protected]>
  • Loading branch information
wiseaidev committed Mar 2, 2022
1 parent bdf0d93 commit d061fe2
Show file tree
Hide file tree
Showing 35 changed files with 94 additions and 126 deletions.
16 changes: 8 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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'),
]

Expand Down
15 changes: 5 additions & 10 deletions docs/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,7 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
# 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)
Expand Down Expand Up @@ -1064,8 +1064,8 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
# 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)
Expand Down Expand Up @@ -1116,12 +1116,7 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
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
Expand Down Expand Up @@ -1175,7 +1170,7 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
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
Expand Down
13 changes: 5 additions & 8 deletions ens/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion ens/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
2 changes: 1 addition & 1 deletion tests/core/contracts/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion tests/core/contracts/test_contract_ambiguous_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
),
(
Expand Down
2 changes: 1 addition & 1 deletion tests/core/contracts/test_contract_call_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
2 changes: 1 addition & 1 deletion tests/core/pm-module/test_ens_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')


Expand Down
8 changes: 4 additions & 4 deletions tests/core/providers/test_auto_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
Expand Down Expand Up @@ -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


Expand All @@ -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
2 changes: 1 addition & 1 deletion tests/core/utilities/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion tests/ens/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 0 additions & 3 deletions web3/_utils/empty.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,5 @@ class Empty:
def __bool__(self) -> Literal[False]:
return False

def __nonzero__(self) -> Literal[False]:
return False


empty = Empty()
6 changes: 3 additions & 3 deletions web3/_utils/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/ens.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 2 additions & 4 deletions web3/_utils/method_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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}"
)


Expand Down
4 changes: 2 additions & 2 deletions web3/_utils/module_testing/eth_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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({})
Expand Down
16 changes: 7 additions & 9 deletions web3/_utils/normalizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/rpc_abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
2 changes: 1 addition & 1 deletion web3/_utils/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
)
8 changes: 4 additions & 4 deletions web3/auto/infura/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Loading

0 comments on commit d061fe2

Please sign in to comment.