Skip to content
Snippets Groups Projects
Verified Commit f4671ee2 authored by Mateusz Żebrak's avatar Mateusz Żebrak
Browse files

Enable ANN401 and fix/ignore current places

parent 4b56d1f3
No related branches found
No related tags found
2 merge requests!399V1.27.5.12 release,!397Bump tools and enable new rules
Showing
with 37 additions and 35 deletions
...@@ -13,7 +13,7 @@ class AbstractClass(ABC): # noqa: B024 ...@@ -13,7 +13,7 @@ class AbstractClass(ABC): # noqa: B024
Even when no abstract methods were defined, this class cannot be instantiated. (default ABC allows for that). Even when no abstract methods were defined, this class cannot be instantiated. (default ABC allows for that).
""" """
def __new__(cls, abstract_type: type[AbstractClass] | None = None, *args: Any, **kwargs: Any) -> Any: def __new__(cls, abstract_type: type[AbstractClass] | None = None, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
abstract_type = AbstractClass if abstract_type is None else abstract_type abstract_type = AbstractClass if abstract_type is None else abstract_type
if abstract_type in cls.__bases__: if abstract_type in cls.__bases__:
raise TypeError(f"Abstract class `{cls.__name__}` cannot be instantiated.") raise TypeError(f"Abstract class `{cls.__name__}` cannot be instantiated.")
...@@ -40,5 +40,5 @@ class AbstractClassMessagePump(AbstractClass, metaclass=MessagePumpABCMeta): ...@@ -40,5 +40,5 @@ class AbstractClassMessagePump(AbstractClass, metaclass=MessagePumpABCMeta):
See the :class:`AbstractClass` class for more details. See the :class:`AbstractClass` class for more details.
""" """
def __new__(cls, *args: Any, **kwargs: Any) -> Any: def __new__(cls, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
return super().__new__(cls, AbstractClassMessagePump, *args, **kwargs) return super().__new__(cls, AbstractClassMessagePump, *args, **kwargs)
...@@ -65,7 +65,7 @@ class CliveTyper(typer.Typer): ...@@ -65,7 +65,7 @@ class CliveTyper(typer.Typer):
no_args_is_help=True, no_args_is_help=True,
) )
def __call__(self, *args: Any, **kwargs: Any) -> Any: def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
try: try:
return super().__call__(*args, **kwargs) return super().__call__(*args, **kwargs)
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
...@@ -90,7 +90,7 @@ class CliveTyper(typer.Typer): ...@@ -90,7 +90,7 @@ class CliveTyper(typer.Typer):
def decorator(f: CommandFunctionType) -> CommandFunctionType: def decorator(f: CommandFunctionType) -> CommandFunctionType:
@wraps(f) @wraps(f)
def wrapper(*args: Any, **_kwargs: Any) -> Any: def wrapper(*args: Any, **_kwargs: Any) -> Any: # noqa: ANN401
if len(args) > 0: if len(args) > 0:
raise RuntimeError("Positional arguments are not supported") raise RuntimeError("Positional arguments are not supported")
...@@ -202,7 +202,7 @@ class CliveTyper(typer.Typer): ...@@ -202,7 +202,7 @@ class CliveTyper(typer.Typer):
return {"ctx": ctx, **kwargs} return {"ctx": ctx, **kwargs}
@staticmethod @staticmethod
def __patch_command_sig(wrapper: Any, common_option: type[CommonOptionsBase]) -> None: def __patch_command_sig(wrapper: Any, common_option: type[CommonOptionsBase]) -> None: # noqa: ANN401
sig = signature(wrapper) sig = signature(wrapper)
new_parameters = sig.parameters.copy() new_parameters = sig.parameters.copy()
......
...@@ -50,11 +50,11 @@ def _get_default_beekeeper_remote() -> str | None: ...@@ -50,11 +50,11 @@ def _get_default_beekeeper_remote() -> str | None:
return None return None
def get_default_or_make_required(value: Any) -> Any: def get_default_or_make_required(value: Any) -> Any: # noqa: ANN401
return ... if value is None else value return ... if value is None else value
def modified_option(option: OptionInfo, **kwargs: Any) -> Any: def modified_option(option: OptionInfo, **kwargs: Any) -> Any: # noqa: ANN401
""" """
Create option based on another option, but with some attributes modified. Create option based on another option, but with some attributes modified.
......
...@@ -18,7 +18,7 @@ def is_token_already_passed(**kwargs: Any) -> bool: ...@@ -18,7 +18,7 @@ def is_token_already_passed(**kwargs: Any) -> bool:
def api(foo: FooT) -> FooT: def api(foo: FooT) -> FooT:
@wraps(foo) @wraps(foo)
async def impl(this: BeekeeperApi, **kwargs: Any) -> Any: async def impl(this: BeekeeperApi, **kwargs: Any) -> Any: # noqa: ANN401
if foo.__name__ not in ["create_session"] and not is_token_already_passed(**kwargs): if foo.__name__ not in ["create_session"] and not is_token_already_passed(**kwargs):
kwargs["token"] = this._owner.token kwargs["token"] = this._owner.token
return ( return (
......
...@@ -63,7 +63,7 @@ class BeekeeperResponseError(BeekeeperError, CommunicationError): ...@@ -63,7 +63,7 @@ class BeekeeperResponseError(BeekeeperError, CommunicationError):
class BeekeeperNotMatchingIdJsonRPCError(BeekeeperError): class BeekeeperNotMatchingIdJsonRPCError(BeekeeperError):
def __init__(self, given: Any, got: Any) -> None: def __init__(self, given: Any, got: Any) -> None: # noqa: ANN401
self.given = given self.given = given
self.got = got self.got = got
message = f"Given id `{given}` does not match the id of the response `{got}`" message = f"Given id `{given}` does not match the id of the response `{got}`"
......
...@@ -14,7 +14,7 @@ def count_parameters(callback: Callable[..., Any]) -> int: ...@@ -14,7 +14,7 @@ def count_parameters(callback: Callable[..., Any]) -> int:
return len(signature(callback).parameters) return len(signature(callback).parameters)
async def invoke(callback: Callable[..., Any], *params: Any) -> Any: async def invoke(callback: Callable[..., Any], *params: Any) -> Any: # noqa: ANN401
""" """
Invoke a callback with an arbitrary number of parameters. Invoke a callback with an arbitrary number of parameters.
......
...@@ -24,7 +24,7 @@ if TYPE_CHECKING: ...@@ -24,7 +24,7 @@ if TYPE_CHECKING:
class CustomJSONEncoder(json.JSONEncoder): class CustomJSONEncoder(json.JSONEncoder):
TIME_FORMAT_WITH_MILLIS: Final[str] = "%Y-%m-%dT%H:%M:%S.%f" TIME_FORMAT_WITH_MILLIS: Final[str] = "%Y-%m-%dT%H:%M:%S.%f"
def default(self, obj: Any) -> Any: def default(self, obj: Any) -> Any: # noqa: ANN401
if isinstance(obj, datetime): if isinstance(obj, datetime):
return obj.strftime(self.TIME_FORMAT_WITH_MILLIS) return obj.strftime(self.TIME_FORMAT_WITH_MILLIS)
...@@ -82,7 +82,7 @@ class Communication: ...@@ -82,7 +82,7 @@ class Communication:
self, self,
url: str, url: str,
*, *,
data: Any, data: Any, # noqa: ANN401
max_attempts: int | None = None, max_attempts: int | None = None,
timeout_secs: float | None = None, timeout_secs: float | None = None,
pool_time_secs: float | None = None, pool_time_secs: float | None = None,
...@@ -109,7 +109,7 @@ class Communication: ...@@ -109,7 +109,7 @@ class Communication:
self, self,
url: str, url: str,
*, *,
data: Any, data: Any, # noqa: ANN401
max_attempts: int | None = None, max_attempts: int | None = None,
timeout_secs: float | None = None, timeout_secs: float | None = None,
pool_time_secs: float | None = None, pool_time_secs: float | None = None,
...@@ -134,7 +134,7 @@ class Communication: ...@@ -134,7 +134,7 @@ class Communication:
self, self,
url: str, url: str,
*, *,
data: Any, data: Any, # noqa: ANN401
max_attempts: int | None = None, max_attempts: int | None = None,
timeout_secs: float | None = None, timeout_secs: float | None = None,
pool_time_secs: float | None = None, pool_time_secs: float | None = None,
...@@ -217,7 +217,7 @@ class Communication: ...@@ -217,7 +217,7 @@ class Communication:
raise CommunicationError(url, data_serialized, result) from exception raise CommunicationError(url, data_serialized, result) from exception
@classmethod @classmethod
def __check_response(cls, url: str, request: str, result: Any) -> None: def __check_response(cls, url: str, request: str, result: Any) -> None: # noqa: ANN401
if isinstance(result, dict): if isinstance(result, dict):
cls.__check_response_item(url=url, request=request, response=result, item=result) cls.__check_response_item(url=url, request=request, response=result, item=result)
elif isinstance(result, list): elif isinstance(result, list):
...@@ -227,7 +227,7 @@ class Communication: ...@@ -227,7 +227,7 @@ class Communication:
raise UnknownResponseFormatError(url, request, result) raise UnknownResponseFormatError(url, request, result)
@classmethod @classmethod
def __check_response_item(cls, url: str, request: str, response: Any, item: JsonT) -> None: def __check_response_item(cls, url: str, request: str, response: Any, item: JsonT) -> None: # noqa: ANN401
if "error" in item: if "error" in item:
logger.debug(f"Error in response from {url=}, request={request}, response={response}") logger.debug(f"Error in response from {url=}, request={request}, response={response}")
raise ErrorInResponseJsonError raise ErrorInResponseJsonError
......
...@@ -24,7 +24,7 @@ def ensure_transaction(content: TransactionConvertibleType) -> Transaction: ...@@ -24,7 +24,7 @@ def ensure_transaction(content: TransactionConvertibleType) -> Transaction:
The transaction. The transaction.
""" """
def __ensure_operation(item: Any) -> Operation: def __ensure_operation(item: Any) -> Operation: # noqa: ANN401
assert isinstance(item, OperationBaseClass) assert isinstance(item, OperationBaseClass)
return item # type: ignore[return-value] return item # type: ignore[return-value]
......
...@@ -19,7 +19,7 @@ class NoMatchesError(CliveError): ...@@ -19,7 +19,7 @@ class NoMatchesError(CliveError):
@overload @overload
def get_default_from_model(model: type[BaseModel] | BaseModel, field_name: str) -> Any: ... def get_default_from_model(model: type[BaseModel] | BaseModel, field_name: str) -> Any: ... # noqa: ANN401
@overload @overload
......
...@@ -54,7 +54,7 @@ class _DelayedResponseWrapper: ...@@ -54,7 +54,7 @@ class _DelayedResponseWrapper:
if self.__get_data() is None: if self.__get_data() is None:
raise ResponseNotReadyError raise ResponseNotReadyError
def __get_data(self) -> Any: def __get_data(self) -> Any: # noqa: ANN401
response = super().__getattribute__("_response") response = super().__getattribute__("_response")
if response is None: if response is None:
return None return None
...@@ -70,11 +70,11 @@ class _DelayedResponseWrapper: ...@@ -70,11 +70,11 @@ class _DelayedResponseWrapper:
response=response, response=response,
) )
def __setattr__(self, __name: str, __value: Any) -> None: def __setattr__(self, __name: str, __value: Any) -> None: # noqa: ANN401
self.__check_is_response_available() self.__check_is_response_available()
setattr(self.__get_data(), __name, __value) setattr(self.__get_data(), __name, __value)
def __getattr__(self, __name: str) -> Any: def __getattr__(self, __name: str) -> Any: # noqa: ANN401
self.__check_is_response_available() self.__check_is_response_available()
return getattr(self.__get_data(), __name) return getattr(self.__get_data(), __name)
......
...@@ -5,7 +5,7 @@ from typing import Any ...@@ -5,7 +5,7 @@ from typing import Any
from pydantic import BaseModel, ValidationError from pydantic import BaseModel, ValidationError
def validate_schema_field(schema_field: type[Any], value: Any) -> None: def validate_schema_field(schema_field: type[Any], value: Any) -> None: # noqa: ANN401
""" """
Validate the given value against the given schema field e.g. one that inherits from pydantic.ConstrainedStr. Validate the given value against the given schema field e.g. one that inherits from pydantic.ConstrainedStr.
...@@ -23,7 +23,7 @@ def validate_schema_field(schema_field: type[Any], value: Any) -> None: ...@@ -23,7 +23,7 @@ def validate_schema_field(schema_field: type[Any], value: Any) -> None:
Model(value=value) Model(value=value)
def is_schema_field_valid(schema_field: type[Any], value: Any) -> bool: def is_schema_field_valid(schema_field: type[Any], value: Any) -> bool: # noqa: ANN401
try: try:
validate_schema_field(schema_field, value) validate_schema_field(schema_field, value)
except ValidationError: except ValidationError:
......
...@@ -77,7 +77,7 @@ class ManageWorkingAccountTable(CliveCheckerboardTable): ...@@ -77,7 +77,7 @@ class ManageWorkingAccountTable(CliveCheckerboardTable):
def object_to_watch(self) -> TextualWorld: def object_to_watch(self) -> TextualWorld:
return self.app.world return self.app.world
def update_previous_state(self, content: Any) -> None: def update_previous_state(self, content: Any) -> None: # noqa: ANN401
self._previous_working_account = content.working_account if _has_working_account(content) else None self._previous_working_account = content.working_account if _has_working_account(content) else None
......
...@@ -281,7 +281,7 @@ class CliveCheckerboardTable(CliveWidget): ...@@ -281,7 +281,7 @@ class CliveCheckerboardTable(CliveWidget):
cell.add_class(ODD_CLASS_NAME) cell.add_class(ODD_CLASS_NAME)
@property @property
def object_to_watch(self) -> Any: def object_to_watch(self) -> Any: # noqa: ANN401
""" """
Must be overridden by the child class when using dynamic table. Must be overridden by the child class when using dynamic table.
......
...@@ -75,7 +75,7 @@ class CliveDataTableRow(Horizontal, CliveWidget): ...@@ -75,7 +75,7 @@ class CliveDataTableRow(Horizontal, CliveWidget):
yield self.RowTitle(self._title) yield self.RowTitle(self._title)
yield from self.cells yield from self.cells
def refresh_row(self, content: Any) -> None: def refresh_row(self, content: Any) -> None: # noqa: ANN401
"""Iterate through the cells and update each of them.""" """Iterate through the cells and update each of them."""
if content is None: # data not received yet if content is None: # data not received yet
return return
...@@ -83,7 +83,7 @@ class CliveDataTableRow(Horizontal, CliveWidget): ...@@ -83,7 +83,7 @@ class CliveDataTableRow(Horizontal, CliveWidget):
for cell, value in zip(self.cells, self.get_new_values(content), strict=True): for cell, value in zip(self.cells, self.get_new_values(content), strict=True):
cell.update(value) cell.update(value)
def get_new_values(self, content: Any) -> tuple[str, ...]: # type: ignore[return] # noqa: ARG002 def get_new_values(self, content: Any) -> tuple[str, ...]: # type: ignore[return] # noqa: ARG002, ANN401
"""Must be overridden if the `dynamic` parameter is set to True.""" """Must be overridden if the `dynamic` parameter is set to True."""
if self._dynamic: if self._dynamic:
raise CliveError("You must override this method if the row is dynamic.") raise CliveError("You must override this method if the row is dynamic.")
...@@ -132,7 +132,7 @@ class CliveDataTable(CliveWidget): ...@@ -132,7 +132,7 @@ class CliveDataTable(CliveWidget):
if self._dynamic: if self._dynamic:
self.watch(self.provider, "_content", self.refresh_rows) self.watch(self.provider, "_content", self.refresh_rows)
def refresh_rows(self, content: Any) -> None: def refresh_rows(self, content: Any) -> None: # noqa: ANN401
if content is None: # data not received yet if content is None: # data not received yet
return return
......
...@@ -70,7 +70,7 @@ class DynamicLabel(CliveWidget): ...@@ -70,7 +70,7 @@ class DynamicLabel(CliveWidget):
return self.__label.renderable return self.__label.renderable
def on_mount(self) -> None: def on_mount(self) -> None:
def delegate_work(old_value: Any, value: Any) -> None: def delegate_work(old_value: Any, value: Any) -> None: # noqa: ANN401
self.run_worker(self.attribute_changed(old_value, value)) self.run_worker(self.attribute_changed(old_value, value))
self.watch(self.__obj_to_watch, self.__attribute_name, delegate_work, self._init) self.watch(self.__obj_to_watch, self.__attribute_name, delegate_work, self._init)
...@@ -78,7 +78,7 @@ class DynamicLabel(CliveWidget): ...@@ -78,7 +78,7 @@ class DynamicLabel(CliveWidget):
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
yield self.__label yield self.__label
async def attribute_changed(self, old_value: Any, value: Any) -> None: async def attribute_changed(self, old_value: Any, value: Any) -> None: # noqa: ANN401
callback = self.__callback callback = self.__callback
if not self._first_try_callback(): if not self._first_try_callback():
......
...@@ -29,7 +29,7 @@ class Transaction(SchemasTransaction): ...@@ -29,7 +29,7 @@ class Transaction(SchemasTransaction):
@validator("operations", pre=True) @validator("operations", pre=True)
@classmethod @classmethod
def convert_operations(cls, value: Any) -> list[OperationRepresentationType]: def convert_operations(cls, value: Any) -> list[OperationRepresentationType]: # noqa: ANN401
assert isinstance(value, list) assert isinstance(value, list)
return [convert_to_representation(op) for op in value] return [convert_to_representation(op) for op in value]
......
...@@ -111,7 +111,6 @@ ignore = [ ...@@ -111,7 +111,6 @@ ignore = [
"TRY003", # Avoid specifying long messages outside the exception class; too restrictive "TRY003", # Avoid specifying long messages outside the exception class; too restrictive
"ANN101", # Missing annotation for self; makes no sense "ANN101", # Missing annotation for self; makes no sense
"ANN102", # Missing annotation for cls; makes no sense "ANN102", # Missing annotation for cls; makes no sense
"ANN401", # Dynamically typed expressions (typing.Any) are disallowed in {name}; TODO: should be enabled, and eventually noqa in place of usage
"TD002", # Missing author in to-do; no need for that "TD002", # Missing author in to-do; no need for that
"TD003", # Missing issue link on the line following this to-do; no need for that "TD003", # Missing issue link on the line following this to-do; no need for that
"SLF001", # Private member accessed: {access}; too restrictive "SLF001", # Private member accessed: {access}; too restrictive
...@@ -124,6 +123,9 @@ ignore = [ ...@@ -124,6 +123,9 @@ ignore = [
"ISC001", # Implicitly concatenated string literals on one line; disabled because conflicts with ruff formatter "ISC001", # Implicitly concatenated string literals on one line; disabled because conflicts with ruff formatter
] ]
[tool.ruff.lint.flake8-annotations]
allow-star-arg-any = true
[tool.ruff.lint.isort] [tool.ruff.lint.isort]
known-first-party = ["clive", "wax", "schemas", "clive_local_tools"] known-first-party = ["clive", "wax", "schemas", "clive_local_tools"]
required-imports = ["from __future__ import annotations"] required-imports = ["from __future__ import annotations"]
......
from __future__ import annotations from __future__ import annotations
from typing import Any, Final from typing import Final
import pytest import pytest
...@@ -32,7 +32,7 @@ PUBLIC_KEY_ALIAS: Final[PublicKeyAliased] = PUBLIC_KEY.with_alias("my_key") ...@@ -32,7 +32,7 @@ PUBLIC_KEY_ALIAS: Final[PublicKeyAliased] = PUBLIC_KEY.with_alias("my_key")
[PUBLIC_KEY_RAW, PUBLIC_KEY, PUBLIC_KEY_ALIAS, PRIVATE_KEY_RAW, PRIVATE_KEY, PRIVATE_KEY_ALIAS], [PUBLIC_KEY_RAW, PUBLIC_KEY, PUBLIC_KEY_ALIAS, PRIVATE_KEY_RAW, PRIVATE_KEY, PRIVATE_KEY_ALIAS],
ids=["public_key_raw", "public_key", "public_key_alias", "private_key_raw", "private_key", "private_key_alias"], ids=["public_key_raw", "public_key", "public_key_alias", "private_key_raw", "private_key", "private_key_alias"],
) )
def test_keys_equal_positive(first: Key, second: Any) -> None: def test_keys_equal_positive(first: Key, second: str | Key) -> None:
# ACT & ASSERT # ACT & ASSERT
assert first == second assert first == second
...@@ -46,7 +46,7 @@ def test_keys_equal_positive(first: Key, second: Any) -> None: ...@@ -46,7 +46,7 @@ def test_keys_equal_positive(first: Key, second: Any) -> None:
"second", "second",
[123, None, [], {}, "5K7WfKML9MDVBKGD7cPXNvHy8zM4bqsoTorqFiMecygbHdrcMhF"], [123, None, [], {}, "5K7WfKML9MDVBKGD7cPXNvHy8zM4bqsoTorqFiMecygbHdrcMhF"],
) )
def test_keys_equal_negative(first: Key, second: Any) -> None: def test_keys_equal_negative(first: Key, second: str | Key) -> None:
# ACT & ASSERT # ACT & ASSERT
assert first != second assert first != second
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment