onl*_*egg 4 python python-3.x python-asyncio mypy
我有几个速率限制器类(其中一个未显示),我想为其创建 ABC。该request方法是一个异步上下文管理器。通过下面显示的代码我得到
“请求”的签名与超类型“RateLimiterInterface”不兼容
如果我尝试用 装饰抽象方法@asynccontextmanager,则会出现输入错误:
“asynccontextmanager”的参数 1 具有不兼容的类型“Callable[[RateLimiterInterface], Coroutine[Any, Any, AsyncIterator[Any]]]”;预期“Callable[...,AsyncIterator[]]”
我怎样才能做到这一点?
class RateLimiterInterface(abc.ABC):
@abc.abstractmethod
async def request(self) -> AsyncIterator:
pass
class LeakyBucketRateLimiter(RateLimiterInterface):
def __init__(self, max_tokens: Optional[int] = None, rate: float = 60) -> None:
self.max_tokens = max_tokens
self.rate = rate
self._bucket = max_tokens
self._last_added_at = time.time()
@contextlib.asynccontextmanager
async def request(self) -> AsyncIterator:
if self._bucket is None:
yield
return
while not self._bucket:
await asyncio.sleep(0)
self._add_tokens(int((time.time() - self._last_added_at) * self.rate))
self._bucket -= 1
yield
return
def _add_tokens(self, num_tokens: int) -> None:
if num_tokens == 0:
return
self._bucket += num_tokens
if self._bucket > self.max_tokens:
self._bucket = self.max_tokens
self._last_added_at = time.time()
Run Code Online (Sandbox Code Playgroud)
我刚刚在打字时遇到了同样的问题并以这种方式解决了它:
import abc
import contextlib
import asyncio
class TestAbstract(metaclass=abc.ABCMeta):
@contextlib.asynccontextmanager
@abc.abstractmethod
# Here the trick: you must declare an asynchronous generator function,
# not a regular coroutine function so it have to explicitly yield.
async def foo(self):
yield
class SubTest(TestAbstract):
@contextlib.asynccontextmanager
async def foo(self):
yield
async def test_coro():
async with SubTest().foo():
print('OK')
asyncio.run(test_coro())
Run Code Online (Sandbox Code Playgroud)