"""演示 asyncio.timeout 与带超时的重试。""" from __future__ import annotations import asyncio async def flaky(calls: list[int], fail_times: int) -> str: calls.append(1) if len(calls) <= fail_times: await asyncio.sleep(0.05) return "ok" async def retry( fail_times: int = 2, attempts: int = 3, timeout: float = 0.02, ) -> tuple[int, str]: calls: list[int] = [] for _ in range(attempts): try: async with asyncio.timeout(timeout): result = await flaky(calls, fail_times) return len(calls), result except TimeoutError: continue raise TimeoutError("all attempts timed out") async def main() -> None: count, result = await retry() print(f"attempts: {count}") print(f"result: {result}") try: await retry(fail_times=5) except TimeoutError as exc: print(f"give up: {exc}") if __name__ == "__main__": asyncio.run(main())