Skip to content

Commit

Permalink
Ruff formatting.
Browse files Browse the repository at this point in the history
  • Loading branch information
rcschrg committed Oct 13, 2024
1 parent c4bd9b6 commit fa215b1
Show file tree
Hide file tree
Showing 28 changed files with 362 additions and 317 deletions.
18 changes: 15 additions & 3 deletions mango/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
from .messages.message import create_acl
from .agent.core import Agent, AgentAddress
from .agent.role import Role, RoleAgent, RoleContext
from .container.factory import create_tcp as create_tcp_container, create_mqtt as create_mqtt_container, create_external_coupling as create_ec_container
from .express.api import activate, run_with_mqtt, run_with_tcp, agent_composed_of, PrintingAgent, sender_addr, addr
from .container.factory import (
create_tcp as create_tcp_container,
create_mqtt as create_mqtt_container,
create_external_coupling as create_ec_container,
)
from .express.api import (
activate,
run_with_mqtt,
run_with_tcp,
agent_composed_of,
PrintingAgent,
sender_addr,
addr,
)
from .util.distributed_clock import DistributedClockAgent, DistributedClockManager
from .util.clock import ExternalClock
from .util.clock import ExternalClock
30 changes: 13 additions & 17 deletions mango/agent/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Every agent must live in a container. Containers are responsible for making
connections to other agents.
"""

import asyncio
import logging
from abc import ABC
Expand All @@ -15,11 +16,13 @@

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class AgentAddress:
addr: Any
aid: str


class AgentContext:
def __init__(self, container) -> None:
self._container = container
Expand Down Expand Up @@ -64,16 +67,14 @@ async def send_message(
class AgentDelegates:
def __init__(self) -> None:
self.context: AgentContext = None
self.scheduler: Scheduler = None
self._aid = None
self.scheduler: Scheduler = None
self._aid = None

def on_start(self):
"""Called when container started in which the agent is contained
"""
"""Called when container started in which the agent is contained"""

def on_ready(self):
"""Called when all container has been started using activate(...).
"""
"""Called when all container has been started using activate(...)."""

@property
def current_timestamp(self) -> float:
Expand Down Expand Up @@ -108,7 +109,6 @@ async def send_message(
content, receiver_addr=receiver_addr, sender_id=self.aid, **kwargs
)


def schedule_instant_message(
self,
content,
Expand All @@ -126,9 +126,7 @@ def schedule_instant_message(
"""

return self.schedule_instant_task(
self.send_message(
content, receiver_addr=receiver_addr, **kwargs
)
self.send_message(content, receiver_addr=receiver_addr, **kwargs)
)

def schedule_conditional_process_task(
Expand Down Expand Up @@ -359,15 +357,15 @@ def __init__(

self.inbox = asyncio.Queue()

@property
@property
def observable_tasks(self):
return self.scheduler.observable

@observable_tasks.setter
def observable_tasks(self, value: bool):
self.scheduler.observable = value
@property

@property
def suspendable_tasks(self):
return self.scheduler.suspendable

Expand All @@ -387,9 +385,7 @@ def _do_register(self, container, aid):
self._aid = aid
self.context = AgentContext(container)
self.scheduler = Scheduler(
suspendable=True,
observable=True,
clock=container.clock
suspendable=True, observable=True, clock=container.clock
)
self.on_register()

Expand Down Expand Up @@ -461,4 +457,4 @@ async def shutdown(self):
except asyncio.CancelledError:
pass
finally:
logger.info("Agent %s: Shutdown successful", self.aid)
logger.info("Agent %s: Shutdown successful", self.aid)
25 changes: 9 additions & 16 deletions mango/agent/role.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,15 +232,16 @@ def subscribe_event(self, role: Role, event_type: type, method: Callable):
self._role_event_type_to_handler[event_type] = []

self._role_event_type_to_handler[event_type] += [(role, method)]

def on_start(self):
for role in self.roles:
role.on_start()

def on_ready(self):
for role in self.roles:
role.on_ready()


class RoleContext(AgentDelegates):
"""Implementation of the RoleContext."""

Expand Down Expand Up @@ -340,7 +341,6 @@ async def send_message(
**kwargs,
)


def emit_event(self, event: Any, event_source: Any = None):
"""Emit an custom event to other roles.
Expand Down Expand Up @@ -375,7 +375,7 @@ def deactivate(self, role) -> None:

def activate(self, role) -> None:
self._role_handler.activate(role)

def on_start(self):
self._role_handler.on_start()

Expand All @@ -388,9 +388,7 @@ class RoleAgent(Agent):
a RoleAgent as base for your agents. A role can be added with :func:`RoleAgent.add_role`.
"""

def __init__(
self
):
def __init__(self):
"""Create a role-agent
:param container: container the agent lives in
Expand All @@ -399,10 +397,8 @@ def __init__(
"""
super().__init__()
self._role_handler = RoleHandler(None, None)
self._role_context = RoleContext(
self._role_handler, self.aid, self.inbox
)

self._role_context = RoleContext(self._role_handler, self.aid, self.inbox)

def on_start(self):
self._role_context.on_start()

Expand Down Expand Up @@ -447,7 +443,6 @@ async def shutdown(self):
await super().shutdown()



class Role(ABC):
"""General role class, defining the API every role can use. A role implements one responsibility
of an agent.
Expand Down Expand Up @@ -501,12 +496,10 @@ async def on_stop(self) -> None:
"""Lifecycle hook in, which will be called when the container is shut down or if the role got removed."""

def on_start(self) -> None:
"""Called when container started in which the agent is contained
"""
"""Called when container started in which the agent is contained"""

def on_ready(self):
"""Called after the start of all container using activate
"""
"""Called after the start of all container using activate"""

def handle_message(self, content: Any, meta: dict):
pass
7 changes: 4 additions & 3 deletions mango/container/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

A = TypeVar("A")


class Container(ABC):
"""Superclass for a mango container"""

Expand Down Expand Up @@ -128,7 +129,7 @@ def register_agent(self, agent: Agent, suggested_aid: str = None):
return aid

def include(self, agent: A, suggested_aid: str = None) -> A:
"""Include the agent in the container. Return the agent for
"""Include the agent in the container. Return the agent for
convenience.
Args:
Expand Down Expand Up @@ -158,14 +159,14 @@ async def send_message(
content: Any,
receiver_addr: AgentAddress,
sender_id: None | str = None,
**kwargs
**kwargs,
) -> bool:
"""
The Container sends a message to an agent according the container protocol.
:param content: The content of the message
:param receiver_addr: The address the message is sent to, should be constructed using
agent_address(protocol_addr, aid) or address(agent) on sending messages,
agent_address(protocol_addr, aid) or address(agent) on sending messages,
and sender_address(meta) on replying to messages.
:param kwargs: Can contain additional meta information
"""
Expand Down
2 changes: 1 addition & 1 deletion mango/container/external_coupling.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ async def send_message(

meta = {}
for key, value in kwargs.items():
meta[key] = value
meta[key] = value
meta["sender_id"] = sender_id
meta["sender_addr"] = self.addr
meta["receiver_id"] = receiver_addr.aid
Expand Down
25 changes: 14 additions & 11 deletions mango/container/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
MQTT_CONNECTION = "mqtt"
EXTERNAL_CONNECTION = "external_connection"

def create_mqtt(broker_addr: tuple | dict | str,

def create_mqtt(
broker_addr: tuple | dict | str,
client_id: str,
codec: Codec = None,
clock: Clock = None,
Expand All @@ -29,7 +31,7 @@ def create_mqtt(broker_addr: tuple | dict | str,
codec = JSON()
if clock is None:
clock = AsyncioClock()

return MQTTContainer(
client_id=client_id,
broker_addr=broker_addr,
Expand All @@ -40,18 +42,19 @@ def create_mqtt(broker_addr: tuple | dict | str,
copy_internal_messages=copy_internal_messages,
**kwargs,
)



def create_external_coupling(
codec: Codec = None,
clock: Clock = None,
addr: None | str | tuple[str, int] = None,
**kwargs: dict[str, Any],
codec: Codec = None,
clock: Clock = None,
addr: None | str | tuple[str, int] = None,
**kwargs: dict[str, Any],
):
if codec is None:
codec = JSON()
if clock is None:
clock = ExternalClock()

return ExternalSchedulingContainer(
addr=addr, loop=asyncio.get_running_loop(), codec=codec, clock=clock, **kwargs
)
Expand All @@ -69,8 +72,8 @@ def create_tcp(
:param codec: Defines the codec to use. Defaults to JSON
:param clock: The clock that the scheduler of the agent should be based on. Defaults to the AsyncioClock
:param addr: the address to use. it has to be a tuple of (host, port).
:param addr: the address to use. it has to be a tuple of (host, port).
:return: The instance of a TCPContainer
"""
if codec is None:
Expand All @@ -79,7 +82,7 @@ def create_tcp(
clock = AsyncioClock()
if isinstance(addr, str):
addr = tuple(addr.split(":"))

# initialize TCPContainer
return TCPContainer(
addr=addr,
Expand Down
2 changes: 1 addition & 1 deletion mango/container/mp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import asyncio
import logging
import os
Expand All @@ -16,6 +15,7 @@

WAIT_STEP = 0.01


class IPCEventType(enumerate):
"""Available IPC event types for event process container communication"""

Expand Down
Loading

0 comments on commit fa215b1

Please sign in to comment.