Skip to content

Commit 4865d68

Browse files
committed
Enable Type Hinting for eth.tools completely
1 parent a0f11f9 commit 4865d68

File tree

19 files changed

+284
-131
lines changed

19 files changed

+284
-131
lines changed

eth/tools/_utils/hashing.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@
77
Tuple,
88
)
99

10+
from eth_typing import (
11+
Hash32,
12+
)
13+
1014
from eth.rlp.logs import Log
1115

1216

13-
def hash_log_entries(log_entries: Iterable[Tuple[bytes, bytes, bytes]]) -> bytes:
17+
def hash_log_entries(log_entries: Iterable[Tuple[bytes, bytes, bytes]]) -> Hash32:
1418
"""
1519
Helper function for computing the RLP hash of the logs from transaction
1620
execution.

eth/tools/_utils/mappings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from cytoolz import merge_with
1111

1212

13-
def merge_if_dicts(values: Sequence[Any]) -> Any:
13+
def merge_if_dicts(values: Sequence[Dict[Any, Any]]) -> Any:
1414
if all(isinstance(item, Mapping) for item in values):
1515
return merge_with(merge_if_dicts, *values)
1616
else:

eth/tools/_utils/normalization.py

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
import binascii
2-
from collections.abc import (
3-
Iterable,
4-
Mapping,
5-
)
62
import functools
73

84
from typing import (
95
Any,
106
AnyStr,
117
Callable,
128
Dict,
9+
Iterable,
1310
List,
11+
Mapping,
1412
Sequence,
1513
Tuple,
1614
)
@@ -58,6 +56,8 @@
5856
from eth.typing import (
5957
AccountState,
6058
GeneralState,
59+
NormalizerType,
60+
TransactionDict,
6161
)
6262

6363

@@ -97,7 +97,7 @@ def normalize_bytes(value: Any) -> bytes:
9797

9898

9999
@functools.lru_cache(maxsize=1024)
100-
def to_int(value: Any) -> int:
100+
def to_int(value: str) -> int:
101101
"""
102102
Robust to integer conversion, handling hex values, string representations,
103103
and special cases like `0x`.
@@ -125,26 +125,22 @@ def normalize_to_address(value: AnyStr) -> Address:
125125
#
126126
# Containers
127127
#
128-
129-
NormalizerType = Callable[[Dict[Any, Any]], Iterable[Tuple[Any, Any]]]
130-
131-
132-
def dict_normalizer(formatters: Dict[Any, Any],
128+
def dict_normalizer(formatters: Dict[Any, Callable[..., Any]],
133129
required: Iterable[Any]=None,
134130
optional: Iterable[Any]=None) -> NormalizerType:
135131

136132
all_keys = set(formatters.keys())
137133

138134
if required is None and optional is None:
139135
required_set_form = all_keys
136+
elif required is not None and optional is not None:
137+
raise ValueError("Both required and optional keys specified")
140138
elif required is not None:
141139
required_set_form = set(required)
142140
elif optional is not None:
143141
required_set_form = all_keys - set(optional)
144-
else:
145-
raise ValueError("Both required and optional keys specified")
146142

147-
def normalizer(d: Dict[Any, Any]) -> Iterable[Tuple[Any, Any]]:
143+
def normalizer(d: Dict[Any, Any]) -> Dict[str, Any]:
148144
keys = set(d.keys())
149145
missing_keys = required_set_form - keys
150146
superfluous_keys = keys - all_keys
@@ -158,9 +154,9 @@ def normalizer(d: Dict[Any, Any]) -> Iterable[Tuple[Any, Any]]:
158154
return normalizer
159155

160156

161-
def dict_options_normalizer(normalizers: Iterable[Callable[..., Any]]) -> Callable[..., Any]:
157+
def dict_options_normalizer(normalizers: Iterable[NormalizerType]) -> NormalizerType:
162158

163-
def normalize(d: Dict[Any, Any]) -> Callable[..., Any]:
159+
def normalize(d: Dict[Any, Any]) -> Dict[str, Any]:
164160
first_exception = None
165161
for normalizer in normalizers:
166162
try:
@@ -251,36 +247,36 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
251247
)
252248

253249

254-
normalize_main_transaction = dict_normalizer({
250+
normalize_main_transaction = dict_normalizer({ # type: ignore # Overwrite type hint not yet supported # noqa: 501
255251
"data": normalize_bytes,
256252
"gasLimit": normalize_int,
257253
"gasPrice": normalize_int,
258254
"nonce": normalize_int,
259255
"secretKey": normalize_bytes,
260256
"to": normalize_to_address,
261257
"value": normalize_int,
262-
})
258+
}) # type: TransactionNormalizer
263259

264260

265-
normalize_transaction = dict_options_normalizer([
261+
normalize_transaction = dict_options_normalizer([ # type: ignore # Overwrite type hint not yet supported # noqa: 501
266262
normalize_main_transaction,
267-
])
263+
]) # type: TransactionNormalizer
268264

269265

270-
normalize_main_transaction_group = dict_normalizer({
266+
normalize_main_transaction_group = dict_normalizer({ # type: ignore # Overwrite type hint not yet supported # noqa: 501
271267
"data": eth_utils.curried.apply_formatter_to_array(normalize_bytes),
272268
"gasLimit": eth_utils.curried.apply_formatter_to_array(normalize_int),
273269
"gasPrice": normalize_int,
274270
"nonce": normalize_int,
275271
"secretKey": normalize_bytes,
276272
"to": normalize_to_address,
277273
"value": eth_utils.curried.apply_formatter_to_array(normalize_int),
278-
})
274+
}) # type: TransactionNormalizer
279275

280276

281-
normalize_transaction_group = dict_options_normalizer([
277+
normalize_transaction_group = dict_options_normalizer([ # type: ignore # Overwrite type hint not yet supported # noqa: 501
282278
normalize_main_transaction_group,
283-
])
279+
]) # type: TransactionNormalizer
284280

285281

286282
normalize_execution = dict_normalizer({
@@ -331,12 +327,12 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
331327
#
332328
# Fixture Normalizers
333329
#
334-
def normalize_unsigned_transaction(transaction: Dict[str, Any],
335-
indexes: Dict[str, Any]) -> Dict[str, Any]:
330+
def normalize_unsigned_transaction(transaction: TransactionDict,
331+
indexes: Dict[str, Any]) -> TransactionDict:
336332

337-
normalized = normalize_transaction_group(transaction)
333+
normalized = normalize_transaction_group(transaction) # type: TransactionDict
338334
return merge(normalized, {
339-
transaction_key: normalized[transaction_key][indexes[index_key]]
335+
transaction_key: normalized[transaction_key][indexes[index_key]] # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
340336
for transaction_key, index_key in [
341337
("gasLimit", "gas"),
342338
("value", "value"),

eth/tools/_utils/vyper.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
Any,
55
Callable,
66
Dict,
7+
List,
78
Tuple,
89
)
910

@@ -30,7 +31,7 @@ def inner(*args: Any, **kwargs: Any) -> Any:
3031

3132

3233
@require_vyper
33-
def compile_vyper_lll(vyper_code: Any) -> Tuple[bytes, Dict[str, Any]]:
34+
def compile_vyper_lll(vyper_code: List[Any]) -> Tuple[bytes, Dict[str, Any]]:
3435
lll_node = LLLnode.from_list(vyper_code)
3536
assembly = compile_to_assembly(lll_node)
3637
code = assembly_to_evm(assembly)

eth/tools/builder/chain/builders.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,23 +92,23 @@ def build(obj: Any, *applicators: Callable[..., Any]) -> Any:
9292
# Constructors (creation of chain classes)
9393
#
9494
@curry
95-
def name(class_name: str, chain_class: BaseChain) -> type:
95+
def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]:
9696
"""
9797
Assign the given name to the chain class.
9898
"""
9999
return chain_class.configure(__name__=class_name)
100100

101101

102102
@curry
103-
def chain_id(chain_id: int, chain_class: BaseChain) -> type:
103+
def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
104104
"""
105105
Set the ``chain_id`` for the chain class.
106106
"""
107107
return chain_class.configure(chain_id=chain_id)
108108

109109

110110
@curry
111-
def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: BaseChain) -> type:
111+
def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
112112
"""
113113
Adds the ``vm_class`` to the chain's ``vm_configuration``.
114114
@@ -168,7 +168,7 @@ def _set_vm_dao_support_false(vm_configuration: VMConfiguration) -> VMConfigurat
168168

169169

170170
@curry
171-
def disable_dao_fork(chain_class: BaseChain) -> type:
171+
def disable_dao_fork(chain_class: Type[BaseChain]) -> Type[BaseChain]:
172172
"""
173173
Set the ``support_dao_fork`` flag to ``False`` on the
174174
:class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of
@@ -199,7 +199,7 @@ def _set_vm_dao_fork_block_number(dao_fork_block_number: int,
199199

200200

201201
@curry
202-
def dao_fork_at(dao_fork_block_number: int, chain_class: BaseChain) -> type:
202+
def dao_fork_at(dao_fork_block_number: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
203203
"""
204204
Set the block number on which the DAO fork will happen. Requires that a
205205
version of the :class:`~eth.vm.forks.homestead.HomesteadVM` is present in
@@ -263,7 +263,7 @@ def _mix_in_pow_mining(vm_configuration: VMConfiguration) -> VMConfiguration:
263263

264264

265265
@curry
266-
def enable_pow_mining(chain_class: BaseChain) -> type:
266+
def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]:
267267
"""
268268
Inject on demand generation of the proof of work mining seal on newly
269269
mined blocks into each of the chain's vms.
@@ -299,7 +299,7 @@ def _mix_in_disable_seal_validation(vm_configuration: VMConfiguration) -> VMConf
299299

300300

301301
@curry
302-
def disable_pow_check(chain_class: Type[BaseChain]) -> type:
302+
def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:
303303
"""
304304
Disable the proof of work validation check for each of the chain's vms.
305305
This allows for block mining without generation of the proof of work seal.

eth/tools/fixtures/_utils.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,26 @@
22
import functools
33
import os
44

5+
from typing import (
6+
Any,
7+
Callable,
8+
Iterable,
9+
)
10+
511
from eth_utils import to_tuple
612

713

814
@to_tuple
9-
def recursive_find_files(base_dir, pattern):
15+
def recursive_find_files(base_dir: str, pattern: str) -> Iterable[str]:
1016
for dirpath, _, filenames in os.walk(base_dir):
1117
for filename in filenames:
1218
if fnmatch.fnmatch(filename, pattern):
1319
yield os.path.join(dirpath, filename)
1420

1521

16-
def require_pytest(fn):
22+
def require_pytest(fn: Callable[..., Any]) -> Callable[..., Any]:
1723
@functools.wraps(fn)
18-
def inner(*args, **kwargs):
24+
def inner(*args: Any, **kwargs: Any) -> Callable[..., Any]:
1925
try:
2026
import pytest # noqa: F401
2127
except ImportError:

eth/tools/fixtures/fillers/_utils.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,29 @@
11
import copy
22
import random
33

4+
from typing import (
5+
Any,
6+
Dict,
7+
List,
8+
Tuple,
9+
Type,
10+
)
11+
12+
from eth_typing import (
13+
Address,
14+
)
15+
416
from eth_utils import (
517
int_to_big_endian,
618
)
719

820
from eth.db.backends.memory import MemoryDB
21+
from eth.db.account import BaseAccountDB
22+
23+
from eth.typing import (
24+
AccountState,
25+
TransactionDict,
26+
)
927

1028
from eth.utils.db import (
1129
apply_state_dict,
@@ -17,13 +35,15 @@
1735
from eth_keys import keys
1836

1937

20-
def wrap_in_list(item):
38+
def wrap_in_list(item: Any) -> List[Any]:
2139
return [item]
2240

2341

24-
def add_transaction_to_group(group, transaction):
42+
def add_transaction_to_group(group: Dict[str, Any],
43+
transaction: TransactionDict) -> Tuple[Dict[str, Any], Dict[str, int]]:
44+
2545
for key in ["gasPrice", "nonce", "secretKey", "to"]:
26-
if key in transaction and transaction[key] != group[key]:
46+
if key in transaction and transaction[key] != group[key]: # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
2747
raise ValueError("Can't add transaction as it differs in {}".format(key))
2848

2949
new_group = copy.deepcopy(group)
@@ -35,26 +55,26 @@ def add_transaction_to_group(group, transaction):
3555
raise ValueError("Can't add transaction as {} is ambiguous".format(key))
3656
index = 0
3757
else:
38-
if transaction[key] not in new_group[key]:
39-
new_group[key].append(transaction[key])
40-
index = new_group[key].index(transaction[key])
58+
if transaction[key] not in new_group[key]: # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
59+
new_group[key].append(transaction[key]) # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
60+
index = new_group[key].index(transaction[key]) # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
4161
indexes[index_key] = index
4262
else:
4363
assert key not in transaction
4464
return new_group, indexes
4565

4666

47-
def calc_state_root(state, account_db_class):
67+
def calc_state_root(state: AccountState, account_db_class: Type[BaseAccountDB]) -> bytes:
4868
account_db = account_db_class(MemoryDB())
4969
apply_state_dict(account_db, state)
5070
return account_db.state_root
5171

5272

53-
def generate_random_keypair():
73+
def generate_random_keypair() -> Tuple[bytes, Address]:
5474
key_object = keys.PrivateKey(pad32(int_to_big_endian(random.getrandbits(8 * 32))))
5575
return key_object.to_bytes(), key_object.public_key.to_canonical_address()
5676

5777

58-
def generate_random_address():
78+
def generate_random_address() -> Address:
5979
_, address = generate_random_keypair()
6080
return address

0 commit comments

Comments
 (0)