Created
September 14, 2020 09:30
-
-
Save cojuer/c88afa9f1d20a0b4d45249a91df8d48e to your computer and use it in GitHub Desktop.
defer-like rollback in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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