Spaces:
Sleeping
Sleeping
File size: 2,054 Bytes
4e067f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# coding: utf-8
# Copyright (c) 2025 inclusionAI.
import asyncio
from functools import wraps
from typing import Callable, Optional, Union, Any, Dict
class Functionable:
def __init__(self, function: Callable[..., Any], *args: Any, **kwargs: Dict[str, Any]) -> None:
self.function = function
self.args = args
self.kwargs = kwargs
self.done: bool = False
self.error: bool = False
self.result: Optional[Any] = None
self.exception: Optional[Exception] = None
def __call__(self) -> None:
try:
self.result = self.function(*self.args, **self.kwargs)
except Exception as e:
self.error = True
self.exception = e
self.done = True
def call(self):
self.__call__()
def async_decorator(*func, delay: Optional[Union[int, float]] = 0.5) -> Callable:
def wrapper(function: Callable[..., Any]) -> Callable[..., Any]:
@wraps(function)
async def inner_wrapper(*args: Any, **kwargs: Any) -> Any:
sleep_time = 0 if delay is None else delay
task = Functionable(function, *args, **kwargs)
# TODO: Use thread pool to process task
task.call()
if task.error:
raise task.exception
await asyncio.sleep(sleep_time)
return task.result
return inner_wrapper
if not func:
return wrapper
else:
if asyncio.iscoroutinefunction(func[0]):
# coroutine function, return itself
return func[0]
return wrapper(func[0])
def async_func(function: Callable[..., Any]) -> Callable[..., Any]:
@wraps(function)
async def inner_wrapper(*args: Any, **kwargs: Any) -> Any:
task = Functionable(function, *args, **kwargs)
task.call()
if task.error:
raise task.exception
return task.result
if asyncio.iscoroutinefunction(function):
# coroutine function, return itself
return function
return inner_wrapper
|