Skip to content

Commit

Permalink
fix: mypy issues
Browse files Browse the repository at this point in the history
  • Loading branch information
angrybayblade committed Jul 6, 2022
1 parent 29587aa commit 6f7b900
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 26 deletions.
4 changes: 1 addition & 3 deletions aea/cli/ipfs_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ def update_hashes(
extend_public_ids(item_config, public_id_to_hash_mappings)
dump_yaml(config_file, item_config, extra_config)

configuration_obj = config_loader(
package_id.package_type.value, package_path
)
configuration_obj = config_loader(package_id.package_type, package_path)
sort_configuration_file(configuration_obj)
update_fingerprint(configuration_obj)
key, package_hash = hash_package(
Expand Down
6 changes: 3 additions & 3 deletions aea/cli/utils/click_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import os
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, List, Optional, Union
from typing import Any, Callable, List, Optional, Union, cast

import click
from click import argument, option
Expand Down Expand Up @@ -132,7 +132,7 @@ def convert(
if parsed_value is None:
self.fail(value, param, ctx)

return parsed_value
return cast(Path, parsed_value)


class PublicIdParameter(click.ParamType):
Expand Down Expand Up @@ -169,7 +169,7 @@ def convert(self, value: str, param: Any, ctx: Optional[click.Context]) -> Publi
if parsed is None:
self.fail(value, param, ctx)

return parsed
return cast(PublicId, parsed)


class AgentDirectory(click.Path):
Expand Down
5 changes: 3 additions & 2 deletions aea/components/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@
import sys
import types
from abc import ABC
from importlib.machinery import ModuleSpec
from pathlib import Path
from typing import Any, Optional
from typing import Any, Optional, cast

from aea.configurations.base import (
ComponentConfiguration,
Expand Down Expand Up @@ -178,7 +179,7 @@ def perform_load_aea_package(
import_path = prefix_pkg + "." + ".".join(relative_parent_dir.parts)

spec = importlib.util.spec_from_file_location(import_path, subpackage_init_file)
module = importlib.util.module_from_spec(spec)
module = importlib.util.module_from_spec(cast(ModuleSpec, spec))
sys.modules[import_path] = module
_default_logger.debug(f"loading {import_path}: {module}")
spec.loader.exec_module(module) # type: ignore
8 changes: 4 additions & 4 deletions aea/helpers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@ def locate(path: str) -> Any:
module_location = os.path.join(file_location, "__init__.py")
spec = importlib.util.spec_from_file_location(spec_name, module_location)
_default_logger.debug("Trying to import {}".format(module_location))
nextmodule = _get_module(spec)
nextmodule = _get_module(cast(ModuleSpec, spec))
if nextmodule is None:
module_location = file_location + ".py"
spec = importlib.util.spec_from_file_location(spec_name, module_location)
_default_logger.debug("Trying to import {}".format(module_location))
nextmodule = _get_module(spec)
nextmodule = _get_module(cast(ModuleSpec, spec))

if nextmodule:
module, n = nextmodule, n + 1
Expand Down Expand Up @@ -125,7 +125,7 @@ def load_module(dotted_path: str, filepath: Path) -> types.ModuleType:
:raises Exception: if the execution of the module raises exception. # noqa: DAR402
"""
spec = importlib.util.spec_from_file_location(dotted_path, str(filepath))
module = importlib.util.module_from_spec(spec)
module = importlib.util.module_from_spec(cast(ModuleSpec, spec))
spec.loader.exec_module(module) # type: ignore
return module

Expand Down Expand Up @@ -530,7 +530,7 @@ def find_topological_order(adjacency_list: Dict[T, Set[T]]) -> List[T]:
# compute the topological order
queue: Deque[T] = deque()
order = []
queue.extendleft(sorted(roots))
queue.extendleft(sorted(roots)) # type: ignore
while len(queue) > 0:
current = queue.pop()
order.append(current)
Expand Down
2 changes: 1 addition & 1 deletion aea/protocols/dialogue/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ class _DialogueMeta(type):
def __new__(cls, name: str, bases: Tuple[Type], dct: Dict) -> "_DialogueMeta":
"""Construct a new type."""
# set class level `_rules`
dialogue_cls: Type[Dialogue] = super().__new__(cls, name, bases, dct)
dialogue_cls: Type[Dialogue] = super().__new__(cls, name, bases, dct) # type: ignore
dialogue_cls._rules = dialogue_cls.Rules(
dialogue_cls.INITIAL_PERFORMATIVES,
dialogue_cls.TERMINAL_PERFORMATIVES,
Expand Down
4 changes: 2 additions & 2 deletions examples/gym_ex/gyms/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
Done = bool
Info = dict

Feedback = Tuple[Observation, Reward, Done, Info]
Feedback = Tuple[Observation, Reward, Done, Info] # type: ignore


class BanditEnv(gym.Env):
Expand Down Expand Up @@ -72,7 +72,7 @@ def __init__(
self.seed() # seed environment randomness

@staticmethod
def reset() -> Observation:
def reset() -> Observation: # type: ignore
"""
Reset the environment.
Expand Down
14 changes: 8 additions & 6 deletions examples/gym_ex/proxy/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ def role_from_first_message( # pylint: disable=unused-argument
class ProxyEnv(gym.Env):
"""This class implements a proxy gym environment."""

_agent_thread: Optional[Thread]

def __init__(self, gym_env: gym.Env) -> None:
"""
Instantiate the proxy environment.
Expand All @@ -106,7 +108,7 @@ def __init__(self, gym_env: gym.Env) -> None:
@property
def active_dialogue(self) -> GymDialogue:
"""Get the active dialogue."""
return self._active_dialogue
return cast(GymDialogue, self._active_dialogue)

def step(self, action: Action) -> Feedback:
"""
Expand Down Expand Up @@ -143,7 +145,7 @@ def render(self, mode="human") -> None:
:param mode: the run mode
"""
self._agent.runtime.multiplexer.default_connection.channel.gym_env.render(mode)
self._agent.runtime.multiplexer.default_connection.channel.gym_env.render(mode) # type: ignore

def reset(self) -> None:
"""Reset the environment."""
Expand All @@ -160,7 +162,7 @@ def reset(self) -> None:
# Wait (blocking!) for the response envelope from the environment
in_envelope = self._queue.get(block=True, timeout=None) # type: GymMessage

self._decode_status(in_envelope)
self._decode_status(cast(Envelope, in_envelope))

def close(self) -> None:
"""Close the environment."""
Expand All @@ -177,17 +179,17 @@ def close(self) -> None:

def _connect(self):
"""Connect to this proxy environment. It starts a proxy agent that can interact with the framework."""
if self._agent_thread.is_alive():
if cast(Thread, self._agent_thread).is_alive():
raise ValueError("Agent already running.")
self._agent_thread.start()
cast(Thread, self._agent_thread).start()

while not self._agent.runtime.is_running: # check agent completely running
time.sleep(0.01)

def _disconnect(self):
"""Disconnect from this proxy environment. It stops the proxy agent and kills its thread."""
self._agent.stop()
self._agent_thread.join()
cast(Thread, self._agent_thread).join()
self._agent_thread = None

def _encode_and_send_action(self, action: Action, step_id: int) -> None:
Expand Down
4 changes: 2 additions & 2 deletions examples/gym_ex/rl/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
Done = bool
Info = dict

Feedback = Tuple[Observation, Reward, Done, Info]
Feedback = Tuple[Observation, Reward, Done, Info] # type: ignore


class PriceBandit:
Expand Down Expand Up @@ -140,7 +140,7 @@ def _pick_an_action(self) -> Action:

def _update_model( # pylint: disable=unused-argument
self,
observation: Observation,
observation: Observation, # type: ignore
reward: Reward,
done: Done,
info: Info,
Expand Down
18 changes: 15 additions & 3 deletions scripts/check_imports_and_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,20 @@
import sys
from collections import defaultdict
from functools import wraps
from importlib.machinery import ModuleSpec
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple, Union
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Union,
cast,
)

from pip._internal.commands.show import search_packages_info # type: ignore

Expand Down Expand Up @@ -165,8 +177,8 @@ def get_section_dependencies_from_setup(cls) -> Dict[str, Dict[str, List[Path]]]
spec = importlib.util.spec_from_file_location(
"setup", str(AEA_ROOT_DIR / "setup.py")
)
setup = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = setup
setup = importlib.util.module_from_spec(cast(ModuleSpec, spec))
sys.modules[cast(ModuleSpec, spec).name] = setup
spec.loader.exec_module(setup) # type: ignore

sections_dependencies = copy.deepcopy(setup.all_extras) # type: ignore
Expand Down
24 changes: 24 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,30 @@ ignore_missing_imports = True
[mypy-google.*]
ignore_missing_imports = True

[mypy-click.*]
ignore_missing_imports = True

[mypy-yaml.*]
ignore_missing_imports = True

[mypy-requests.*]
ignore_missing_imports = True

[mypy-certifi.*]
ignore_missing_imports = True

[mypy-werkzeug.*]
ignore_missing_imports = True

[mypy-pkg_resources.*]
ignore_missing_imports = True

[mypy-gyms.*]
ignore_missing_imports = True

[mypy-rl.*]
ignore_missing_imports = True

[darglint]
docstring_style=sphinx
strictness=short
Expand Down

0 comments on commit 6f7b900

Please sign in to comment.