Skip to content

Instantly share code, notes, and snippets.

@stigok
Created October 13, 2025 08:53
Show Gist options
  • Save stigok/214d2b482d495def4daa367e44f299d6 to your computer and use it in GitHub Desktop.
Save stigok/214d2b482d495def4daa367e44f299d6 to your computer and use it in GitHub Desktop.
An attempt to create a decorator for spending at least n seconds before returning from an awaitable/
import asyncio
from functools import wraps
from typing import Any
from collections.abc import Awaitable
def await_at_least(fn: Awaitable[Any], *, seconds: int):
"""
Do not return from the decorated function until at least `seconds`
have passed.
"""
@wraps(fn)
async def wrapper(*args, **kwargs):
async with asyncio.TaskGroup() as group:
group.create_task(asyncio.sleep(seconds))
task = group.create_task(fn(*args, **kwargs))
return task.result()
return wrapper
@await_at_least(seconds=5)
async def foo():
print("foo: sleeping for 3 seconds")
await asyncio.sleep(3)
print("foo: done sleeping for 3 seconds")
print("about to do something for at least 5 seconds")
await foo()
print("done something for at least 5 secs!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment