|
| 1 | +from collections.abc import Callable |
| 2 | +from functools import wraps |
| 3 | +from inspect import iscoroutinefunction |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from injection._core.common.asynchronous import Caller |
| 7 | +from injection._core.module import Module, mod |
| 8 | + |
| 9 | + |
| 10 | +def asfunction[**P, T]( |
| 11 | + wrapped: type[Callable[P, T]] | None = None, |
| 12 | + /, |
| 13 | + *, |
| 14 | + module: Module | None = None, |
| 15 | + threadsafe: bool = False, |
| 16 | +) -> Any: |
| 17 | + module = module or mod() |
| 18 | + |
| 19 | + def decorator(wp: type[Callable[P, T]]) -> Callable[P, T]: |
| 20 | + get_method = wp.__call__.__get__ |
| 21 | + method = get_method(NotImplemented) |
| 22 | + factory: Caller[..., Callable[P, T]] = module.make_injected_function( |
| 23 | + wp, |
| 24 | + threadsafe=threadsafe, |
| 25 | + ).__inject_metadata__ |
| 26 | + |
| 27 | + wrapper: Callable[P, T] |
| 28 | + |
| 29 | + if iscoroutinefunction(method): |
| 30 | + |
| 31 | + @wraps(method) |
| 32 | + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> Any: |
| 33 | + self = await factory.acall() |
| 34 | + return await get_method(self)(*args, **kwargs) |
| 35 | + |
| 36 | + else: |
| 37 | + |
| 38 | + @wraps(method) |
| 39 | + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: |
| 40 | + self = factory.call() |
| 41 | + return get_method(self)(*args, **kwargs) |
| 42 | + |
| 43 | + wrapper.__name__ = wp.__name__ |
| 44 | + wrapper.__qualname__ = wp.__qualname__ |
| 45 | + return wrapper |
| 46 | + |
| 47 | + return decorator(wrapped) if wrapped else decorator |
0 commit comments