Async Context Manager in Python
Level 5350 keystrokes
This creates an async context manager using __aenter__ and __aexit__. Used with 'async with' for asynchronous resource management.
Python code
# Import asyncio for async/await support# Provides event loop and async utilities1import asyncio2 # class AsyncResource is an async context manager# Manages resources that need async setup/teardown3class AsyncResource: # __aenter__ is async version of __enter__ # Called when entering 'async with' block4 async def __aenter__(self): # Print acquisition message5 print("Acquiring resource") # Simulate async operation like network/file6 await asyncio.sleep(0.1) # Return self for 'as' variable7 return self8 # __aexit__ is async version of __exit__ # *args captures exception info if any9 async def __aexit__(self, *args): # Print release message10 print("Releasing resource") # Simulate async cleanup11 await asyncio.sleep(0.1)12 # use is a regular async method # Called while resource is acquired13 async def use(self):14 print("Using resource")15 # main is an async function (coroutine)# Entry point for async code16async def main(): # 'async with' calls __aenter__ and __aexit__ # r is the returned value from __aenter__17 async with AsyncResource() as r: # Call use() while resource is held18 await r.use()19 # asyncio.run() creates event loop and runs main# Standard way to run async code20asyncio.run(main())Output
Acquiring resource Using resource Releasing resource
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 13)× 13_× 8:× 6.× 6"× 6,× 1*× 1