Skip to content

Commit

Permalink
🐛 Bug Fix && let lazy easilier to use
Browse files Browse the repository at this point in the history
  • Loading branch information
H2Sxxa committed Sep 1, 2024
1 parent 77942fc commit 57d6ea9
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 10 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "saleyo"
version = "1.2.0"
version = "1.2.1"
description = "Saleyo is a lightwight scalable Python AOP framework, easy to use and integrate."
authors = [{ name = "H2Sxxa", email = "[email protected]" }]
dependencies = []
Expand Down
15 changes: 12 additions & 3 deletions src/saleyo/base/import_broadcast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,24 @@ def add_listen_import(
listener: Callable[[str, ModuleType], Any],
key: Optional[str] = None,
disposable: bool = False,
dispose_token_rev: Optional[Callable[[Union[int, str]], Any]] = None,
):
listeners = _disposable_listeners if disposable else _listeners

hashkey = key if key else hash(listener)
if hashkey in listeners:
raise Exception(f"{hashkey} Duplicate!")

if dispose_token_rev:
dispose_token_rev(hashkey)

listeners[hashkey] = listener


def list_import_listeners(disposable: bool = False):
return _disposable_listeners if disposable else _listeners


def remove_listen_import(
key: Union[str, Callable[[str, ModuleType], Any]],
disposable: bool = False,
Expand Down Expand Up @@ -55,10 +64,10 @@ def initialize_import_broadcast():
class ImportBroadCastDict(type(sys.modules)):
def __setitem__(self, key: str, value: ModuleType) -> None:
# BroadCast
for listener in _listeners.values():
for listener in _listeners.copy().values():
listener(key, value)
# disposable
for hashkey, listener in _disposable_listeners.items():
# Disposable
for hashkey, listener in _disposable_listeners.copy().items():
listener(key, value)
del _disposable_listeners[hashkey]

Expand Down
1 change: 0 additions & 1 deletion src/saleyo/decorator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@

from .ancestor import Ancestor as Ancestor
from .mixin import Mixin as Mixin
from . import lazy as lazy
Empty file removed src/saleyo/decorator/lazy.py
Empty file.
50 changes: 46 additions & 4 deletions src/saleyo/decorator/mixin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from types import ModuleType
from typing import Callable, Generic, Iterable, List, Optional, Union

from saleyo.base.import_broadcast import remove_listen_import

from ..base.template import MixinOperation
from ..base.toolchain import DefaultToolChain, ToolChain
from ..base.typing import IterableOrSingle, M, T
Expand Down Expand Up @@ -111,13 +113,38 @@ def from_regex(

@staticmethod
def lazy(
factory: Callable[[str, ModuleType], Optional[IterableOrSingle[M]]],
toolchain: ToolChain = DefaultToolChain,
reverse_level: bool = False,
key: Optional[str] = None,
initialize: bool = True,
auto_dispose: bool = True,
disposable: bool = False,
) -> Callable[[object], Union[int, str]]:
"""
See `Mixin.lazy_mixin`
"""
return lambda mixin: Mixin.lazy_mixin(
mixin,
factory,
toolchain,
reverse_level,
key,
initialize,
auto_dispose,
disposable,
)

@staticmethod
def lazy_mixin(
mixin: object,
factory: Callable[[str, ModuleType], Optional[IterableOrSingle[M]]],
toolchain: ToolChain = DefaultToolChain,
reverse_level: bool = False,
key: Optional[str] = None,
initialize: bool = True,
disposable: bool = True,
auto_dispose: bool = True,
disposable: bool = False,
) -> Union[int, str]:
"""
Please call lazy before import a module.
Expand All @@ -130,7 +157,9 @@ def lazy(
key: specific the key of listener, you can remove it yourself
disposable: remove listener after first Mixin
auto_dispose: remove listener after first Mixin
disposable: remove listener after importing first module
"""
from saleyo.base.import_broadcast import (
initialize_import_broadcast,
Expand All @@ -140,14 +169,27 @@ def lazy(
if initialize:
initialize_import_broadcast()

token = None

def rev(message):
nonlocal token
token = message

def listener(k, v):
target = factory(k, v)
if target:
Mixin(
target=target, toolchain=toolchain, reverse_level=reverse_level
).apply_from_class(mixin)

add_listen_import(listener, key, disposable=disposable)
if token:
remove_listen_import(token, disposable=disposable)

add_listen_import(
listener,
key,
disposable=disposable,
dispose_token_rev=rev if auto_dispose else None,
)
return key if key else hash(listener)

def apply_from_class(self, mixin: T) -> T:
Expand Down
26 changes: 26 additions & 0 deletions tests/test_import_broadcast/lazymix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from types import ModuleType
from saleyo.base.import_broadcast import list_import_listeners
from saleyo.decorator.mixin import Mixin
from saleyo.operation.hook import Pre


def locater(name: str, module: ModuleType):
if name == "targetmod":
if module.__dict__.__contains__("NeedLazyMixin"):
return module.NeedLazyMixin
return None


@Mixin.lazy(locater)
class MixinTarget:
@Pre
def hello(self):
print("Pre Hook")


print(list_import_listeners())
import targetmod as targetmod # noqa: E402

print(list_import_listeners())

targetmod.NeedLazyMixin().hello()
Empty file.
3 changes: 3 additions & 0 deletions tests/test_import_broadcast/targetmod.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class NeedLazyMixin:
def hello(self):
print("hello world")
2 changes: 1 addition & 1 deletion tests/test_import_broadcast/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


def something():
import module as module
import targetmod as targetmod


something()

0 comments on commit 57d6ea9

Please sign in to comment.