Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 0xjgv/600575bcec28ff58e7d41f29a75f590e to your computer and use it in GitHub Desktop.
Save 0xjgv/600575bcec28ff58e7d41f29a75f590e to your computer and use it in GitHub Desktop.
[Python Async Decorator] #python #asyncio #decorator
import asyncio
import time
from functools import wraps
def dec(fn):
if asyncio.iscoroutinefunction(fn):
@wraps(fn)
async def wrapper(*args, **kwargs):
print(fn, args, kwargs) # <function foo at 0x10952d598> () {}
await asyncio.sleep(5)
print("done with wrapper, going to call fn")
return await fn()
return wrapper
else:
@wraps(fn)
def wrapper(*args, **kwargs):
print(fn, args, kwargs) # <function bar at 0x108fb5a60> () {}
time.sleep(5)
print("done with wrapper, going to call fn")
return fn()
return wrapper
@dec
async def foo():
return await asyncio.sleep(5, result="async function done")
@dec
def bar():
time.sleep(5)
return "sync function done"
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())
print(result) # async function done
print(bar()) # sync function done
loop.close()
import asyncio
from functools import wraps
def dec(fn):
@wraps(fn)
async def wrapper(*args, **kwargs):
print(fn, args, kwargs) # <function foo at 0x10952d598> () {}
await asyncio.sleep(5)
print("done with wrapper, going to call fn")
return await fn()
return wrapper
@dec
async def foo():
return await asyncio.sleep(5, result="i'm done")
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())
print(result) # i'm done
loop.close()
import asyncio
from functools import wraps
async def foo():
return await asyncio.sleep(5, result="i'm done")
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())
print(result) # i'm done
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment