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

...
# open a context manager
with ContextManager() as manager:
	# ...
# closed automatically
  • The above code which equal to

...
# 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

# 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

Last updated

Was this helpful?