Skip to content

Commit ece65fe

Browse files
authored
Update Asynchrony_and_Concurrency_Python.md
1 parent 158ce58 commit ece65fe

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Asynchrony_and_Concurrency_Python.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,31 @@ asyncio.run(main())
206206
```
207207
In this example, we create an event loop using asyncio.get_event_loop() and schedule a task using loop.create_task(my_task()). The event loop is then run using loop.run_forever() which schedules and runs the task as soon as resources become available.
208208

209+
### 🔶 10. What is the purpose of the async with statement in Python? Provide an example?
210+
211+
---
212+
#### Answer
213+
The async with statement is used for managing resources in an asynchronous context, similar to the regular with statement for synchronous code. It's commonly used for working with asynchronous I/O resources that need to be acquired and released safely.
214+
215+
#### Example:
216+
```python
217+
import asyncio
218+
219+
class AsyncResource:
220+
async def __aenter__(self):
221+
print("Acquiring resource asynchronously")
222+
await asyncio.sleep(1)
223+
return self
224+
225+
async def __aexit__(self, exc_type, exc_val, exc_tb):
226+
print("Releasing resource asynchronously")
227+
228+
async def main():
229+
async with AsyncResource() as resource:
230+
print("Using async resource")
231+
232+
if __name__ == "__main__":
233+
asyncio.run(main())
234+
```
235+
209236
### <a href="#top"> Back to top ⬆️</a>

0 commit comments

Comments
 (0)