Skip to content

Commit f08b381

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

File tree

19 files changed

+277
-122
lines changed

19 files changed

+277
-122
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: 20 additions & 23 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,9 @@
5856
from eth.typing import (
5957
AccountState,
6058
GeneralState,
59+
NormalizerType,
60+
TransactionDict,
61+
TransactionNormalizer,
6162
)
6263

6364

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

9899

99100
@functools.lru_cache(maxsize=1024)
100-
def to_int(value: Any) -> int:
101+
def to_int(value: str) -> int:
101102
"""
102103
Robust to integer conversion, handling hex values, string representations,
103104
and special cases like `0x`.
@@ -125,26 +126,22 @@ def normalize_to_address(value: AnyStr) -> Address:
125126
#
126127
# Containers
127128
#
128-
129-
NormalizerType = Callable[[Dict[Any, Any]], Iterable[Tuple[Any, Any]]]
130-
131-
132-
def dict_normalizer(formatters: Dict[Any, Any],
129+
def dict_normalizer(formatters: Dict[Any, Callable[..., Any]],
133130
required: Iterable[Any]=None,
134131
optional: Iterable[Any]=None) -> NormalizerType:
135132

136133
all_keys = set(formatters.keys())
137134

138135
if required is None and optional is None:
139136
required_set_form = all_keys
137+
elif required is not None and optional is not None:
138+
raise ValueError("Both required and optional keys specified")
140139
elif required is not None:
141140
required_set_form = set(required)
142141
elif optional is not None:
143142
required_set_form = all_keys - set(optional)
144-
else:
145-
raise ValueError("Both required and optional keys specified")
146143

147-
def normalizer(d: Dict[Any, Any]) -> Iterable[Tuple[Any, Any]]:
144+
def normalizer(d: Dict[Any, Any]) -> Dict[str, Any]:
148145
keys = set(d.keys())
149146
missing_keys = required_set_form - keys
150147
superfluous_keys = keys - all_keys
@@ -158,9 +155,9 @@ def normalizer(d: Dict[Any, Any]) -> Iterable[Tuple[Any, Any]]:
158155
return normalizer
159156

160157

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

163-
def normalize(d: Dict[Any, Any]) -> Callable[..., Any]:
160+
def normalize(d: Dict[Any, Any]) -> Dict[str, Any]:
164161
first_exception = None
165162
for normalizer in normalizers:
166163
try:
@@ -251,7 +248,7 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
251248
)
252249

253250

254-
normalize_main_transaction = dict_normalizer({
251+
normalize_main_transaction: TransactionNormalizer = dict_normalizer({ # type: ignore # Overwrite type hint not yet supported # noqa: 501
255252
"data": normalize_bytes,
256253
"gasLimit": normalize_int,
257254
"gasPrice": normalize_int,
@@ -262,12 +259,12 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
262259
})
263260

264261

265-
normalize_transaction = dict_options_normalizer([
262+
normalize_transaction: TransactionNormalizer = dict_options_normalizer([ # type: ignore # Overwrite type hint not yet supported # noqa: 501
266263
normalize_main_transaction,
267264
])
268265

269266

270-
normalize_main_transaction_group = dict_normalizer({
267+
normalize_main_transaction_group: TransactionNormalizer = dict_normalizer({ # type: ignore # Overwrite type hint not yet supported # noqa: 501
271268
"data": eth_utils.curried.apply_formatter_to_array(normalize_bytes),
272269
"gasLimit": eth_utils.curried.apply_formatter_to_array(normalize_int),
273270
"gasPrice": normalize_int,
@@ -278,7 +275,7 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
278275
})
279276

280277

281-
normalize_transaction_group = dict_options_normalizer([
278+
normalize_transaction_group: TransactionNormalizer = dict_options_normalizer([ # type: ignore # Overwrite type hint not yet supported # noqa: 501
282279
normalize_main_transaction_group,
283280
])
284281

@@ -331,12 +328,12 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
331328
#
332329
# Fixture Normalizers
333330
#
334-
def normalize_unsigned_transaction(transaction: Dict[str, Any],
335-
indexes: Dict[str, Any]) -> Dict[str, Any]:
331+
def normalize_unsigned_transaction(transaction: TransactionDict,
332+
indexes: Dict[str, Any]) -> TransactionDict:
336333

337-
normalized = normalize_transaction_group(transaction)
334+
normalized = normalize_transaction_group(transaction) # type: TransactionDict
338335
return merge(normalized, {
339-
transaction_key: normalized[transaction_key][indexes[index_key]]
336+
transaction_key: normalized[transaction_key][indexes[index_key]] # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501
340337
for transaction_key, index_key in [
341338
("gasLimit", "gas"),
342339
("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)