Context Managers in Python
Learn how context managers help Python programs manage resources safely and automatically.
What is a Context Manager?
A context manager is used to manage resources such as files, database connections and other operations that need proper setup and cleanup.
Python commonly uses the with statement
to work with context managers.
Context Manager Flow
Start Operation
Resource is opened or prepared.
with Block
The required operation is performed.
Cleanup
The resource is properly released.
The with Statement
The with statement is the most common
way to use a context manager in Python.
with open("students.txt", "r") as file:
data = file.read()
print(data)
After the with block finishes, Python
automatically handles the file resource.
Simple File Example
with open("students.txt", "w") as file:
file.write("Rahul")
print("File operation completed")
Output:
File operation completed
The file is automatically closed after the
with block.
Without a Context Manager
Without using with, we have to manually
close the file.
file = open("students.txt", "r")
data = file.read()
print(data)
file.close()
Forgetting to close a resource can cause problems, especially when working with many resources.
with vs Manual Resource Handling
Manual Handling
The programmer must explicitly release the resource.
file = open("data.txt", "r")
data = file.read()
file.close()
Context Manager
Python automatically handles the resource.
with open("data.txt", "r") as file:
data = file.read()
Creating a Custom Context Manager
A custom context manager can be created using the
__enter__() and __exit__()
methods.
class Demo:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with Demo():
print("Inside context")
Output:
Entering context
Inside context
Exiting context
__enter__ Method
The __enter__() method runs when Python
enters the with block.
class Demo:
def __enter__(self):
print("Context started")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Context ended")
with Demo():
print("Working")
The __enter__() method is used for
setup operations.
__exit__ Method
The __exit__() method runs when Python
leaves the with block.
It is commonly used for cleanup operations.
Context Manager with Exception
class Demo:
def __enter__(self):
print("Context started")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Context ended")
with Demo():
print("Inside context")
raise ValueError("Something went wrong")
The __exit__() method still gets a chance
to run when an exception occurs inside the
with block.
Example 👀👨🏫
File handling is one of the most common practical uses of context managers.
with open("students.txt", "r") as file:
for line in file:
print(line.strip())
Python automatically handles the file resource when
the with block finishes.
Common Uses of Context Managers
Files
Open and safely close files automatically.
Database
Manage database connections and transactions.
Resources
Manage resources that require proper cleanup.
Advantages of Context Managers
Automatic Cleanup
Resources are properly handled after use.
Safer Code
Reduces the chance of forgetting cleanup operations.
Cleaner Code
Resource management becomes simpler and clearer.
Best Practices
Use with
Prefer the with statement for supported resources.
Cleanup Resources
Make sure resources are properly released.
Keep It Simple
Use custom context managers only when needed.
Common Mistakes
- Forgetting to close resources when not using a context manager.
- Using a custom context manager when a built-in context manager is enough.
- Putting unrelated operations inside the with block.
- Not understanding the purpose of __enter__ and __exit__.
Practice Programs
-
Read a text file using the
withstatement. - Write data to a file using a context manager.
-
Create a custom context manager using
__enter__()and__exit__(). - Create a context manager that prints messages when entering and leaving a block.
- Create a context manager that handles a resource safely when an exception occurs.
Summary
Context managers are used to manage resources safely
in Python. The with statement is the
most common way to use a context manager. Custom
context managers can be created using
__enter__() and __exit__().
They help make programs safer, cleaner and easier
to maintain.