Skip to content

Commit

Permalink
0.2.7
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Feb 10, 2022
1 parent 9dff0d7 commit 537556f
Show file tree
Hide file tree
Showing 14 changed files with 433 additions and 370 deletions.
18 changes: 18 additions & 0 deletions arclet/letoderea/depend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from typing import Callable, Coroutine

from .entities.decorator import TemplateDecorator
from .entities.subscriber import Subscriber
from .utils import ArgumentPackage
from .handler import await_exec_target


class Depend(TemplateDecorator):
target: Subscriber

def __init__(self, callable_func: Callable):
super().__init__(keep=False)
self.target = Subscriber(callable_func)

def supply(self, target_argument: ArgumentPackage) -> Coroutine:
coro = await_exec_target(self.target, target_argument.value)
return coro
2 changes: 1 addition & 1 deletion arclet/letoderea/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ class PropagationCancelled(Exception):
pass


class ExecutionStop(Exception):
class ParsingStop(Exception):
pass
22 changes: 14 additions & 8 deletions arclet/letoderea/handler.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import traceback
from typing import Tuple, Dict, Type, Any, Union, Callable
from typing import Tuple, Dict, Type, Any, Union, Callable, List
from .entities.subscriber import Subscriber
from .entities.event import Insertable, ParamRet
from .exceptions import UndefinedRequirement, UnexpectedArgument, MultipleInserter, RepeatedInserter, ExecutionStop, \
from .exceptions import UndefinedRequirement, UnexpectedArgument, MultipleInserter, RepeatedInserter, ParsingStop, \
PropagationCancelled
from .utils import argument_analysis, run_always_await
from .utils import argument_analysis, run_always_await, Empty
from .entities.decorator import TemplateDecorator


Expand All @@ -24,13 +24,13 @@ async def await_exec_target(
event_data = ((), {})
try:
event_args = before_parser(decorators, event_data)
arguments = param_parser(target_param, event_args)
arguments = await param_parser(target_param, event_args)
real_arguments = after_parser(decorators, arguments)
result = await run_always_await(callable_target, **real_arguments)
except (UnexpectedArgument, UndefinedRequirement):
traceback.print_exc()
raise
except (ExecutionStop, PropagationCancelled):
except (ParsingStop, PropagationCancelled):
raise
except Exception as e:
traceback.print_exc()
Expand Down Expand Up @@ -77,12 +77,15 @@ def before_parser(decorators, event_data):
return event_args


def param_parser(params, event_args):
async def param_parser(
params: List[Tuple[str, Any, Any]],
event_args: Dict[str, Any],
) -> Dict[str, Any]:
"""
将调用函数提供的参数字典与事件提供的参数字典进行比对,并返回正确的参数字典
Args:
params: 调用的函数的参数字典
params: 调用的函数的参数列表
event_args: 函数可返回的参数字典
Returns:
函数需要的参数字典
Expand All @@ -97,10 +100,13 @@ def param_parser(params, event_args):
arguments_dict.setdefault(name, event_args.get(annotation.__name__))
elif name in event_args:
arguments_dict.setdefault(name, event_args[name])
elif default is not None:
elif default is not Empty:
arguments_dict[name] = default
if isinstance(default, Callable):
arguments_dict[name] = default()
elif isinstance(default, TemplateDecorator) and default.__class__.__name__ == "Depend":
__depend_result = default.supply_wrapper("event_data", event_args)
arguments_dict[name] = await __depend_result['event_data']
elif values := list(filter(lambda x: isinstance(x, annotation), event_args.values())):
arguments_dict[name] = values[0]
if name not in arguments_dict:
Expand Down
3 changes: 2 additions & 1 deletion arclet/letoderea/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .entities.condition import TemplateCondition
from .entities.event import TemplateEvent

Empty = inspect.Signature.empty
Event_T = Union[Type[TemplateEvent], TemplateEvent]
Condition_T = Union[Type[TemplateCondition], TemplateCondition]

Expand Down Expand Up @@ -41,7 +42,7 @@ def argument_analysis(callable_target: Callable):
(
name,
param.annotation if param.annotation is not inspect.Signature.empty else None,
param.default if param.default is not inspect.Signature.empty else None,
param.default # if param.default is not inspect.Signature.empty else None,
)
for name, param in inspect.signature(callable_target).parameters.items()
]
Expand Down
116 changes: 58 additions & 58 deletions dev_tools/breakpoint.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,58 @@
import asyncio
from arclet.letoderea import EventSystem
from arclet.letoderea.entities.event import TemplateEvent
from arclet.letoderea.breakpoint.stepout import StepOut
from arclet.letoderea.breakpoint import Breakpoint

loop = asyncio.get_event_loop()
test_stack = [0]
es = EventSystem(loop=loop)
break_point = Breakpoint(event_system=es)


class TestStepOut(StepOut):

@staticmethod
def handler(msg: str):
if msg == "continue!":
print(msg)
return msg


class ExampleEvent(TemplateEvent):
type: str = "ExampleEvent"
msg: str

def get_params(self):
return self.param_export(
str=self.msg
)


@es.register(ExampleEvent)
async def test(m: str):
if m == 'hello':
print("wait for msg:'continue!' ")
await break_point(TestStepOut(ExampleEvent))
print(m)


a = ExampleEvent()
a.msg = "hello"
b = ExampleEvent()
b.msg = "continue!"


async def main():
for i in range(0, 4):
if i % 2 == 0:
print('>>> event posted with msg: "hello"')
es.event_spread(a)
else:
print('>>> event posted with msg: "continue!"')
es.event_spread(b)
await asyncio.sleep(1)


loop.run_until_complete(main())
import asyncio
from arclet.letoderea import EventSystem
from arclet.letoderea.entities.event import TemplateEvent
from arclet.letoderea.breakpoint.stepout import StepOut
from arclet.letoderea.breakpoint import Breakpoint

loop = asyncio.get_event_loop()
test_stack = [0]
es = EventSystem(loop=loop)
break_point = Breakpoint(event_system=es)


class TestStepOut(StepOut):

@staticmethod
def handler(msg: str):
if msg == "continue!":
print(msg)
return msg


class ExampleEvent(TemplateEvent):
type: str = "ExampleEvent"
msg: str

def get_params(self):
return self.param_export(
str=self.msg
)


@es.register(ExampleEvent)
async def test(m: str):
if m == 'hello':
print("wait for msg:'continue!' ")
await break_point(TestStepOut(ExampleEvent))
print(m)


a = ExampleEvent()
a.msg = "hello"
b = ExampleEvent()
b.msg = "continue!"


async def main():
for i in range(0, 4):
if i % 2 == 0:
print('>>> event posted with msg: "hello"')
es.event_spread(a)
else:
print('>>> event posted with msg: "continue!"')
es.event_spread(b)
await asyncio.sleep(1)


loop.run_until_complete(main())

95 changes: 49 additions & 46 deletions dev_tools/condition.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,49 @@
from datetime import datetime
from arclet.letoderea.entities.condition import TemplateCondition
import asyncio
from arclet.letoderea import EventSystem
from arclet.letoderea.entities.event import TemplateEvent


loop = asyncio.get_event_loop()
test_stack = [0]
es = EventSystem(loop=loop)


class TestCondition(TemplateCondition):

def __init__(self, hour, minute):
self.hour = hour
self.minute = minute

def judge(self, *args, **kwargs) -> bool:
now = datetime.now()
return now > datetime(year=now.year, month=now.month, day=now.day, hour=self.hour, minute=self.minute)


class ExampleEvent(TemplateEvent):
type: str = "ExampleEvent"
msg: int

def get_params(self):
return self.param_export(
int=self.msg
)


@es.register(ExampleEvent, conditions=[TestCondition(23, 30)])
async def test(a: str = "hello"):
for i in range(5):
await asyncio.sleep(0.1)
print(a)
loop.stop()


b = ExampleEvent()
b.msg = 1
es.event_spread(b)
loop.run_forever()

from datetime import datetime
from arclet.letoderea.entities.condition import TemplateCondition
import asyncio
from arclet.letoderea import EventSystem
from arclet.letoderea.entities.event import TemplateEvent


loop = asyncio.get_event_loop()
test_stack = [0]
es = EventSystem(loop=loop)


class TestCondition(TemplateCondition):

def __init__(self, hour, minute):
self.hour = hour
self.minute = minute

def judge(self, *args, **kwargs) -> bool:
now = datetime.now()
return now > datetime(year=now.year, month=now.month, day=now.day, hour=self.hour, minute=self.minute)


class ExampleEvent(TemplateEvent):
type: str = "ExampleEvent"
msg: int

def get_params(self):
return self.param_export(
int=self.msg
)


@es.register(ExampleEvent, conditions=[TestCondition(22, 30)])
async def test(a: str = "hello"):
print(a)


b = ExampleEvent()
b.msg = 1


async def main():
for i in range(5):
await asyncio.sleep(0.1)
es.event_spread(b)

loop.run_until_complete(main())

Loading

0 comments on commit 537556f

Please sign in to comment.