CodingNic

Intermediate Python

Context Managers

Intermediate Python 34 min read

Context Managers

Context Managers

You have used code like this before:

python
with open("notes.txt") as file:
    text = file.read()

The with keyword is using a context manager.

Context managers help manage resources safely.

What Is a Context Manager?

A context manager is an object that sets something up, lets you use it, then cleans it up automatically.

Examples:

  • open a file, then close it
  • connect to something, then disconnect
  • lock a resource, then release it

Why Context Managers Matter

They help you:

  • write cleaner code
  • avoid forgetting cleanup
  • handle resources safely
  • reduce errors

File Example Without with

python
file = open("notes.txt")
text = file.read()
file.close()

You must remember to close the file.

File Example With with

python
with open("notes.txt") as file:
    text = file.read()

The file closes automatically.

How It Works

A context manager has special methods:

  • __enter__()
  • __exit__()

Python runs them when entering and leaving the with block.

Create Your Own Context Manager

python
class Message:
    def __enter__(self):
        print("Start")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("End")

with Message():
    print("Inside")

Output

text
Start
Inside
End

Using as Variable

python
class Tool:
    def __enter__(self):
        print("Open")
        return "Ready"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Close")

with Tool() as status:
    print(status)

Output

text
Open
Ready
Close

Even If Error Happens

__exit__() still runs.

That makes cleanup reliable.

Why This Is Powerful

Useful for:

  • files
  • database connections
  • timers
  • locks
  • temporary settings

Code Along

Create a context manager that prints:

  • Begin
  • Working
  • Finish

Mini Challenge

Create class Session.

Tasks:

  • __enter__() prints:
text
Login
  • __exit__() prints:
text
Logout

Inside the with block print:

text
Using account

Expected output:

text
Login
Using account
Logout

Real World Use Case

Programs use context managers for files, databases, transactions, locks, and temporary resources.

Quiz

  1. What does a context manager do?
  2. Why is with useful?
  3. What methods power custom context managers?
  4. Does cleanup happen after errors too?

Assignment

Create a custom context manager that prints Start and End around a block.

Summary

You learned how context managers use with to manage setup and cleanup automatically.