# Context Manager

## Introduction

* A Python context manager is a tool used to manage resources efficiently, ensuring proper setup and teardown of actions. The `with` statement is commonly used with context managers to define a block of code where resources are acquired, used, and then released automatically. such as client session, file resource

```python
...
# open a context manager
with ContextManager() as manager:
	# ...
# closed automatically
```

* The above code which equal to

```python
...
# create the object
manager = ContextManager()
try:
	manager.__enter__()
	# ...
finally:
	manager.__exit__()
```

* `__enter__` and `__exit__` methods are standard method to let you declare your customization logic when setting up and closing of your context manager class

## Example

```python
# SuperFastPython.com
# example of an asynchronous context manager via async with
import asyncio
 
# define an asynchronous context manager
class AsyncContextManager:
    # enter the async context manager
    async def __aenter__(self):
        # report a message
        print('>entering the context manager')
        # block for a moment
        await asyncio.sleep(0.5)
 
    # exit the async context manager
    async def __aexit__(self, exc_type, exc, tb):
        # report a message
        print('>exiting the context manager')
        # block for a moment
        await asyncio.sleep(0.5)
 
# define a simple coroutine
async def custom_coroutine():
    # create and use the asynchronous context manager
    async with AsyncContextManager() as manager:
        # report the result
        print(f'within the manager')
 
# start the asyncio program
asyncio.run(custom_coroutine())
```

* Output

```
>entering the context manager
within the manager
>exiting the context manager
```

## References

{% embed url="https://github.com/Jwindler/Ice_story/blob/main/src/python/Asyncio/Asyncio_17.md" %}

{% embed url="https://bbc.github.io/cloudfit-public-docs/asyncio/asyncio-part-3.html" %}
