Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Context Manager Types
Python context managers enable automatic resource management using the with statement. They define what happens when entering and exiting a runtime context, ensuring proper cleanup of resources like files, database connections, or locks.
Context managers implement two special methods to define their behavior ?
The __enter__() Method
The __enter__() method is called when entering the runtime context. It sets up the resource and returns an object that will be assigned to the variable after the as keyword in the with statement.
class SimpleContext:
def __enter__(self):
print("Entering context")
return "Resource object"
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")
return False
with SimpleContext() as resource:
print(f"Using: {resource}")
Entering context Using: Resource object Exiting context
The __exit__() Method
The __exit__(exc_type, exc_val, exc_tb) method is called when exiting the context. It receives three parameters for exception handling and returns a boolean indicating whether to suppress any exceptions that occurred.
class ErrorHandlingContext:
def __enter__(self):
print("Setting up resource")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
print(f"Exception occurred: {exc_val}")
return True # Suppress the exception
print("Clean exit")
return False
# Normal execution
with ErrorHandlingContext():
print("Normal operation")
print("---")
# With exception
with ErrorHandlingContext():
raise ValueError("Something went wrong")
print("Program continues")
Setting up resource Normal operation Clean exit --- Setting up resource Exception occurred: Something went wrong Program continues
File Manager Example
Here's a practical example of a custom file manager context ?
class FileManager:
def __init__(self, filename, mode='r'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
print(f"Opening file: {self.filename}")
# Create a sample file for demo
with open(self.filename, 'w') as f:
f.write("Sample content\nLine 2\nLine 3")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
return False
# Using the custom context manager
with FileManager('demo.txt') as f:
content = f.read()
print("File content:")
print(content)
Opening file: demo.txt File content: Sample content Line 2 Line 3 Closing file: demo.txt
Key Benefits
| Benefit | Description |
|---|---|
| Automatic Cleanup | Resources are always properly released |
| Exception Safety | Cleanup occurs even if exceptions are raised |
| Code Clarity | Clear separation of setup and teardown logic |
Conclusion
Context managers provide a clean way to manage resources automatically. Implement __enter__() for setup and __exit__() for cleanup to ensure proper resource management even when exceptions occur.
