Context Managers
Context Managers
You have used code like this before:
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
file = open("notes.txt")
text = file.read()
file.close()
You must remember to close the file.
File Example With with
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
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
Start
Inside
End
Using as Variable
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
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:
Login
__exit__()prints:
Logout
Inside the with block print:
Using account
Expected output:
Login
Using account
Logout
Real World Use Case
Programs use context managers for files, databases, transactions, locks, and temporary resources.
Quiz
- What does a context manager do?
- Why is
withuseful? - What methods power custom context managers?
- 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.