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 utilities
1import asyncio
2
# class AsyncResource is an async context manager
# Manages resources that need async setup/teardown
3class AsyncResource:
# __aenter__ is async version of __enter__
# Called when entering 'async with' block
4 async def __aenter__(self):
# Print acquisition message
5 print("Acquiring resource")
# Simulate async operation like network/file
6 await asyncio.sleep(0.1)
# Return self for 'as' variable
7 return self
8
# __aexit__ is async version of __exit__
# *args captures exception info if any
9 async def __aexit__(self, *args):
# Print release message
10 print("Releasing resource")
# Simulate async cleanup
11 await asyncio.sleep(0.1)
12
# use is a regular async method
# Called while resource is acquired
13 async def use(self):
14 print("Using resource")
15
# main is an async function (coroutine)
# Entry point for async code
16async 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 held
18 await r.use()
19
# asyncio.run() creates event loop and runs main
# Standard way to run async code
20asyncio.run(main())

Output

Acquiring resource
Using resource
Releasing resource
Practice typing this code

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

More Python examples at level 5

← Python typing practice