Skip to content

Instantly share code, notes, and snippets.

@cojuer
Created September 14, 2020 09:30
Show Gist options
  • Save cojuer/c88afa9f1d20a0b4d45249a91df8d48e to your computer and use it in GitHub Desktop.
Save cojuer/c88afa9f1d20a0b4d45249a91df8d48e to your computer and use it in GitHub Desktop.
defer-like rollback in python
import asyncio
from contextlib import AsyncExitStack
async def a():
print('step A')
async def roll_a():
print('rollback step A')
async def b():
print('step B')
async def roll_b():
print('rollback step B')
async def test():
async with AsyncExitStack() as stack:
await a()
stack.push_async_exit(lambda *exc: roll_a())
await b()
stack.push_async_exit(lambda *exc: roll_b())
stack.pop_all()
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment