Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions injection/_core/common/lazy.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,50 @@
from collections.abc import Callable, Iterator
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from functools import partial

from injection._core.common.invertible import Invertible, SimpleInvertible
from injection._core.common.invertible import Invertible


def lazy[T](factory: Callable[..., T]) -> Invertible[T]:
def lazy[T](factory: Callable[..., T]) -> Callable[[], T]:
def cache() -> Iterator[T]:
nonlocal factory
value = factory()
del factory
while True:
yield value

return partial(next, cache())


def alazy[T](factory: Callable[..., Awaitable[T]]) -> Callable[[], Awaitable[T]]:
async def cache() -> AsyncIterator[T]:
value = await factory()
while True:
yield value

getter = partial(next, cache())
return SimpleInvertible(getter)
return partial(_anext, cache())


class Lazy[T](Invertible[T]):
__slots__ = ("__invertible", "__is_set")
__slots__ = ("__get", "__is_set")

__invertible: Invertible[T]
__get: Callable[[], T]
__is_set: bool

def __init__(self, factory: Callable[..., T]) -> None:
@lazy
def invertible() -> T:
def get() -> T:
value = factory()
self.__is_set = True
return value

self.__invertible = invertible
self.__get = get
self.__is_set = False

def __invert__(self) -> T:
return ~self.__invertible
return self.__get()

@property
def is_set(self) -> bool:
return self.__is_set


async def _anext[T](async_iterator: AsyncIterator[T]) -> T:
return await anext(async_iterator)
6 changes: 3 additions & 3 deletions injection/_core/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
from injection._core.common.event import Event, EventChannel, EventListener
from injection._core.common.invertible import Invertible, SimpleInvertible
from injection._core.common.key import new_short_key
from injection._core.common.lazy import Lazy, lazy
from injection._core.common.lazy import Lazy, alazy, lazy
from injection._core.common.threading import get_lock
from injection._core.common.type import (
InputType,
Expand Down Expand Up @@ -512,9 +512,9 @@ def constant[**P, T](
mode: Mode | ModeStr = Mode.get_default(),
) -> Any:
def decorator(wp: Recipe[P, T]) -> Recipe[P, T]:
lazy_instance = lazy(wp)
recipe: Recipe[[], T] = alazy(wp) if iscoroutinefunction(wp) else lazy(wp) # type: ignore[arg-type]
self.injectable(
lambda: ~lazy_instance,
recipe,
ignore_type_hint=True,
inject=False,
on=(wp, on),
Expand Down
29 changes: 28 additions & 1 deletion tests/test_constant.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest

from injection import constant, get_instance
from injection import aget_instance, constant, get_instance


class TestConstant:
Expand All @@ -12,6 +12,33 @@ class SomeInjectable: ...
instance_2 = get_instance(SomeInjectable)
assert instance_1 is instance_2 is not None

def test_constant_with_recipe(self):
class SomeClass: ...

@constant
def recipe() -> SomeClass:
return SomeClass()

instance_1 = get_instance(SomeClass)
instance_2 = get_instance(SomeClass)
assert instance_1 is instance_2
assert isinstance(instance_1, SomeClass)

async def test_constant_with_async_recipe(self):
class SomeClass: ...

@constant
async def recipe() -> SomeClass:
return SomeClass()

with pytest.raises(RuntimeError):
get_instance(SomeClass)

instance_1 = await aget_instance(SomeClass)
instance_2 = await aget_instance(SomeClass)
assert instance_1 is instance_2
assert isinstance(instance_1, SomeClass)

def test_constant_with_on(self):
class A: ...

Expand Down