context

Python Context Managers

Python Context Managers

Context managers allow you to manage resources efficiently, ensuring that they are properly acquired and released. They are often used in file handling and database connections.

Using with Statement

The with statement simplifies the management of resources:

      
        with open("example.txt", "r") as file:
            content = file.read()
            print(content)
      
    

The file is automatically closed after the with block, even if an exception is raised.

Creating Custom Context Managers

You can create custom context managers using the contextlib module:

      
        from contextlib import contextmanager

        @contextmanager
        def my_context_manager():
            print("Entering the context")
            yield
            print("Exiting the context")

        with my_context_manager():
            print("Inside the context")
      
    

This custom context manager prints messages before and after the block is executed.

Activity

Try It Yourself!

Create a context manager that opens a file for writing and ensures it is closed after writing to it.

Quick Quiz

Quick Quiz

  1. What does the with statement do?
  2. How can you create a custom context manager in Python?

Answers: The with statement ensures proper resource management. You can create a custom context manager using the @contextmanager decorator from the contextlib module.