Python Mastery – From Basics to Brilliance / Advanced Python Topics

Context Managers

πŸ”„ Context Managers

A context manager is used to manage resources automatically, such as files, database connections, or network connections.

The most common way to use one is with the with statement.


πŸ“‚ Using with

Instead of manually opening and closing a file:

file = open("data.txt", "r")

content = file.read()

file.close()

We can use a context manager:

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

Python automatically closes the file when the with block finishes.


πŸ”Ή Creating a Context Manager

A class can act as a context manager using:

__enter__()
__exit__()

Example:

class MyContext:
    def __enter__(self):
        print("Entering")

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting")

with MyContext():
    print("Inside")
Entering
Inside
Exiting

Here:

__enter__() β†’ Runs when entering the with block
__exit__()  β†’ Runs when leaving the with block

with β†’ Setup β†’ Use β†’ Cleanup automatically πŸ”„