Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change linting to use pre-commit #3297

Merged
merged 15 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions ens/ens.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ def get_text(self, name: str, key: str) -> str:

r = self.resolver(name)
_validate_resolver_and_interface_id(name, r, ENS_TEXT_INTERFACE_ID, "text")
return r.caller.text(node, key)
return cast(str, r.caller.text(node, key))

def set_text(
self,
Expand Down Expand Up @@ -561,7 +561,9 @@ def _setup_reverse(

def _reverse_registrar(self) -> "Contract":
addr = self.ens.caller.owner(normal_name_to_hash(REVERSE_REGISTRAR_DOMAIN))
return self.w3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR)
return cast(
"Contract", self.w3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR)
)

def _set_property(
self,
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ use_parentheses = true
check_untyped_defs = true
disallow_any_generics = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_subclassing_any = false
pacrob marked this conversation as resolved.
Show resolved Hide resolved
disallow_untyped_calls = true
disallow_untyped_decorators = false
disallow_untyped_defs = true
ignore_missing_imports = true
strict_equality = true
strict_optional = false
warn_redundant_casts = true
warn_return_any = true
warn_return_any = false
warn_unused_configs = true
warn_unused_ignores = true

Expand Down
4 changes: 1 addition & 3 deletions web3/_utils/abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,7 @@ def from_type_str(
) -> "ExactLengthBytesEncoder":
subencoder_cls = cls.get_subencoder_class()
subencoder = subencoder_cls.from_type_str(abi_type.to_type_str(), registry)
# type ignored b/c @parse_type_str decorator turns it into a classmethod,
# so mypy thinks cls(...) is a call to __call__, but actually calls __init__
return cls( # type: ignore
return cls(
subencoder,
value_bit_size=abi_type.sub * 8,
data_byte_size=abi_type.sub,
Expand Down
2 changes: 1 addition & 1 deletion web3/_utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Callable[..., Any]:
category=DeprecationWarning,
stacklevel=2,
)
return to_wrap(*args, **kwargs)
return cast(Callable[..., Any], to_wrap(*args, **kwargs))

return cast(TFunc, wrapper)

Expand Down
3 changes: 1 addition & 2 deletions web3/_utils/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,7 @@ async def deploy(self, async_w3: "AsyncWeb3") -> "AsyncLogFilter":

def initialize_event_topics(event_abi: ABIEvent) -> Union[bytes, List[Any]]:
if event_abi["anonymous"] is False:
# https://github.com/python/mypy/issues/4976
return event_abi_to_log_topic(event_abi) # type: ignore
return event_abi_to_log_topic(event_abi)
else:
return list()

Expand Down
18 changes: 11 additions & 7 deletions web3/_utils/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Iterable,
Tuple,
TypeVar,
cast,
)

from eth_typing import (
Expand Down Expand Up @@ -46,11 +47,14 @@ def hex_to_integer(value: HexStr) -> int:
def apply_formatters_to_args(
*formatters: Callable[[TValue], TReturn]
) -> Callable[..., TReturn]:
return compose(
*(
apply_formatter_at_index(formatter, index)
for index, formatter in enumerate(formatters)
)
return cast(
Callable[..., TReturn],
compose(
*(
apply_formatter_at_index(formatter, index)
for index, formatter in enumerate(formatters)
)
),
)


Expand Down Expand Up @@ -79,7 +83,7 @@ def recursive_map(func: Callable[..., TReturn], data: Any) -> TReturn:
"""

def recurse(item: Any) -> TReturn:
return recursive_map(func, item)
return cast(TReturn, recursive_map(func, item))

items_mapped = map_collection(recurse, data)
return func(items_mapped)
Expand Down Expand Up @@ -128,6 +132,6 @@ def remove_key_if(
key: Any, remove_if: Callable[[Dict[Any, Any]], bool], input_dict: Dict[Any, Any]
) -> Dict[Any, Any]:
if key in input_dict and remove_if(input_dict):
return dissoc(input_dict, key)
return cast(Dict[Any, Any], dissoc(input_dict, key))
else:
return input_dict
27 changes: 17 additions & 10 deletions web3/_utils/module_testing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,17 @@ def __init__(
] = w3.provider.make_request

def __enter__(self) -> "Self":
self.w3.provider.make_request = self._mock_request_handler
# mypy error: Cannot assign to a method
self.w3.provider.make_request = self._mock_request_handler # type: ignore[method-assign] # noqa: E501
# reset request func cache to re-build request_func with mocked make_request
self.w3.provider._request_func_cache = (None, None)

return self

# define __exit__ with typing information
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
self.w3.provider.make_request = self._make_request
# mypy error: Cannot assign to a method
self.w3.provider.make_request = self._make_request # type: ignore[method-assign] # noqa: E501
# reset request func cache to re-build request_func with original make_request
self.w3.provider._request_func_cache = (None, None)

Expand Down Expand Up @@ -158,21 +160,24 @@ def _mock_request_handler(
# If the original make_request was decorated, we need to re-apply
# the decorator to the mocked make_request. This is necessary for
# the request caching decorator to work properly.
return decorator(lambda *_: mocked_response)(
self.w3.provider, method, params
return cast(
"RPCResponse",
decorator(lambda *_: mocked_response)(self.w3.provider, method, params),
)
else:
return mocked_response
return cast("RPCResponse", mocked_response)

# -- async -- #
async def __aenter__(self) -> "Self":
self.w3.provider.make_request = self._async_mock_request_handler
# mypy error: Cannot assign to a method
self.w3.provider.make_request = self._async_mock_request_handler # type: ignore[method-assign] # noqa: E501
# reset request func cache to re-build request_func with mocked make_request
self.w3.provider._request_func_cache = (None, None)
return self

async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
self.w3.provider.make_request = self._make_request
# mypy error: Cannot assign to a method
self.w3.provider.make_request = self._make_request # type: ignore[method-assign] # noqa: E501
# reset request func cache to re-build request_func with original make_request
self.w3.provider._request_func_cache = (None, None)

Expand Down Expand Up @@ -241,11 +246,13 @@ async def _async_mock_request_handler(
async def _coro(
_provider: Any, _method: "RPCEndpoint", _params: Any
) -> "RPCResponse":
return mocked_result
return cast("RPCResponse", mocked_result)

return await decorator(_coro)(self.w3.provider, method, params)
return cast(
"RPCResponse", await decorator(_coro)(self.w3.provider, method, params)
)
else:
return mocked_result
return cast("RPCResponse", mocked_result)

@staticmethod
def _create_error_object(error: Dict[str, Any]) -> Dict[str, Any]:
Expand Down
6 changes: 3 additions & 3 deletions web3/contract/base_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,9 +793,9 @@ def get_function_by_selector(
self, selector: Union[bytes, int, HexStr]
) -> "BaseContractFunction":
def callable_check(fn_abi: ABIFunction) -> bool:
# typed dict cannot be used w/ a normal Dict
# https://github.com/python/mypy/issues/4976
return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(selector) # type: ignore # noqa: E501
return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(
selector
)

fns = self.find_functions_by_identifier(
self.abi, self.w3, self.address, callable_check
Expand Down
9 changes: 6 additions & 3 deletions web3/datastructures.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ def _apply_if_mapping(cls: Type[T], value: TValue) -> Union[T, TValue]:

@classmethod
def recursive(cls, value: TValue) -> "ReadableAttributeDict[TKey, TValue]":
return recursive_map(cls._apply_if_mapping, value)
return cast(
"ReadableAttributeDict[TKey, TValue]",
recursive_map(cls._apply_if_mapping, value),
)


class MutableAttributeDict(
Expand Down Expand Up @@ -243,7 +246,7 @@ def replace(self, old: TKey, new: TKey) -> TValue:
self._replace_with_new_name(old, new)
else:
self._queue[old_name] = new
return to_be_replaced
return cast(TValue, to_be_replaced)

def _repr_if_not_hashable(self, value: TKey) -> TKey:
try:
Expand Down Expand Up @@ -295,7 +298,7 @@ def __contains__(self, element: Any) -> bool:

def __getitem__(self, element: TKey) -> TValue:
element_name = self._repr_if_not_hashable(element)
return self._queue[element_name]
return cast(TValue, self._queue[element_name])

def __len__(self) -> int:
return len(self._queue)
Expand Down
3 changes: 2 additions & 1 deletion web3/eth/async_eth.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,8 @@ async def unsubscribe(self, subscription_id: HexStr) -> bool:
# -- contract methods -- #

@overload
def contract(self, address: None = None, **kwargs: Any) -> Type[AsyncContract]:
# mypy error: Overloaded function signatures 1 and 2 overlap with incompatible return types # noqa: E501
def contract(self, address: None = None, **kwargs: Any) -> Type[AsyncContract]: # type: ignore[misc] # noqa: E501
...

@overload
Expand Down
3 changes: 2 additions & 1 deletion web3/eth/eth.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,8 @@ def modify_transaction(
)

@overload
def contract(self, address: None = None, **kwargs: Any) -> Type[Contract]:
# type error: Overloaded function signatures 1 and 2 overlap with incompatible return types # noqa: E501
def contract(self, address: None = None, **kwargs: Any) -> Type[Contract]: # type: ignore[misc] # noqa: E501
...

@overload
Expand Down
2 changes: 1 addition & 1 deletion web3/gas_strategies/time_based.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def _get_avg_block_time(w3: Web3, sample_size: int) -> float:
raise Web3ValidationError("Constrained sample size is 0")

oldest = w3.eth.get_block(BlockNumber(latest["number"] - constrained_sample_size))
return (latest["timestamp"] - oldest["timestamp"]) / constrained_sample_size
return float((latest["timestamp"] - oldest["timestamp"]) / constrained_sample_size)


def _get_weighted_avg_block_time(w3: Web3, sample_size: int) -> float:
Expand Down
24 changes: 12 additions & 12 deletions web3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,14 @@ def middleware_onion(self) -> MiddlewareOnion:
def to_bytes(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> bytes:
return to_bytes(primitive, hexstr, text)
return cast(bytes, to_bytes(primitive, hexstr, text))
pacrob marked this conversation as resolved.
Show resolved Hide resolved

@staticmethod
@wraps(to_int)
def to_int(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> int:
return to_int(primitive, hexstr, text)
return cast(int, to_int(primitive, hexstr, text))

@staticmethod
@wraps(to_hex)
Expand All @@ -223,7 +223,7 @@ def to_hex(
def to_text(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> str:
return to_text(primitive, hexstr, text)
return cast(str, to_text(primitive, hexstr, text))

@staticmethod
@wraps(to_json)
Expand All @@ -239,18 +239,18 @@ def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei:
@staticmethod
@wraps(from_wei)
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
return from_wei(number, unit)
return cast(Union[int, decimal.Decimal], from_wei(number, unit))

# Address Utility
@staticmethod
@wraps(is_address)
def is_address(value: Any) -> bool:
return is_address(value)
return cast(bool, is_address(value))

@staticmethod
@wraps(is_checksum_address)
def is_checksum_address(value: Any) -> bool:
return is_checksum_address(value)
return cast(bool, is_checksum_address(value))

@staticmethod
@wraps(to_checksum_address)
Expand Down Expand Up @@ -285,7 +285,7 @@ def keccak(
) -> bytes:
if isinstance(primitive, (bytes, int, type(None))):
input_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
return eth_utils_keccak(input_bytes)
return cast(bytes, eth_utils_keccak(input_bytes))

raise Web3TypeError(
f"You called keccak with first arg {primitive!r} and keywords "
Expand All @@ -298,7 +298,7 @@ def keccak(
def normalize_values(
cls, w3: "BaseWeb3", abi_types: List[TypeStr], values: List[Any]
) -> List[Any]:
return map_abi_data([abi_ens_resolver(w3)], abi_types, values)
return cast(List[Any], map_abi_data([abi_ens_resolver(w3)], abi_types, values))

@combomethod
def solidity_keccak(cls, abi_types: List[TypeStr], values: List[Any]) -> bytes:
Expand Down Expand Up @@ -327,7 +327,7 @@ def solidity_keccak(cls, abi_types: List[TypeStr], values: List[Any]) -> bytes:
)
)
)
return cls.keccak(hexstr=hex_string)
return cast(bytes, cls.keccak(hexstr=hex_string))

def attach_modules(
self, modules: Optional[Dict[str, Union[Type[Module], Sequence[Any]]]]
Expand All @@ -338,7 +338,7 @@ def attach_modules(
_attach_modules(self, modules)

def is_encodable(self, _type: TypeStr, value: Any) -> bool:
return self.codec.is_encodable(_type, value)
return cast(bool, self.codec.is_encodable(_type, value))


class Web3(BaseWeb3):
Expand Down Expand Up @@ -389,7 +389,7 @@ def provider(self, provider: BaseProvider) -> None:

@property
def client_version(self) -> str:
return self.manager.request_blocking(RPC.web3_clientVersion, [])
return cast(str, self.manager.request_blocking(RPC.web3_clientVersion, []))

@property
def ens(self) -> Union[ENS, "Empty"]:
Expand Down Expand Up @@ -456,7 +456,7 @@ def provider(self, provider: AsyncBaseProvider) -> None:

@property
async def client_version(self) -> str:
return await self.manager.coro_request(RPC.web3_clientVersion, [])
return cast(str, await self.manager.coro_request(RPC.web3_clientVersion, []))

@property
def ens(self) -> Union[AsyncENS, "Empty"]:
Expand Down
11 changes: 7 additions & 4 deletions web3/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def apply_error_formatters(
) -> RPCResponse:
if error_formatters:
formatted_resp = pipe(response, error_formatters)
return formatted_resp
return cast(RPCResponse, formatted_resp)
else:
return response

Expand All @@ -112,7 +112,7 @@ def apply_null_result_formatters(
) -> RPCResponse:
if null_result_formatters:
formatted_resp = pipe(params, null_result_formatters)
return formatted_resp
return cast(RPCResponse, formatted_resp)
else:
return response

Expand Down Expand Up @@ -402,7 +402,10 @@ async def _process_response(self, response: RPCResponse) -> RPCResponse:
error_formatters,
null_formatters,
)
return apply_result_formatters(result_formatters, partly_formatted_response)
return cast(
RPCResponse,
apply_result_formatters(result_formatters, partly_formatted_response),
)


class _AsyncPersistentMessageStream:
Expand All @@ -424,6 +427,6 @@ def __aiter__(self) -> Self:

async def __anext__(self) -> RPCResponse:
try:
return await self.manager._get_next_message()
return cast(RPCResponse, await self.manager._get_next_message())
except ConnectionClosedOK:
raise StopAsyncIteration