GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python __exit__ Method - Complete Guide Python __exit__ MethodLast modified April 8, 2025
This comprehensive guide explores Python's Basic Definitions
The
Key characteristics: it's called when exiting the Basic Context Manager
Here's a simple context manager demonstrating basic_exit.py
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
print("File closed successfully")
with FileManager('example.txt', 'w') as f:
f.write('Hello, World!')
This example shows a file manager that automatically closes the file. The
The three parameters in Handling Exceptions
exception_handling.py
class SafeDivide:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ZeroDivisionError:
print("Division by zero prevented")
return True # Suppress the exception
return False # Propagate other exceptions
with SafeDivide():
result = 10 / 0 # Normally raises ZeroDivisionError
print("Continuing after division") # This line executes
This context manager suppresses
Returning Database Connection Manager
A common use case for db_connection.py
import sqlite3
class DatabaseConnection:
def __init__(self, db_name):
self.db_name = db_name
self.conn = None
def __enter__(self):
self.conn = sqlite3.connect(self.db_name)
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
if self.conn:
if exc_type: # An exception occurred
self.conn.rollback()
else:
self.conn.commit()
self.conn.close()
print("Database connection closed")
with DatabaseConnection('test.db') as conn:
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
This database manager commits changes if no exceptions occur, but rolls back
if there's an error. The
The example shows how Multiple Resource Management
multiple_resources.py
class MultiResourceManager:
def __enter__(self):
print("Acquiring resource 1")
print("Acquiring resource 2")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Releasing resource 2")
print("Releasing resource 1")
if exc_type:
print(f"Error occurred: {exc_val}")
return False
with MultiResourceManager():
print("Working with resources")
# raise ValueError("Test error") # Uncomment to test error case
This manager demonstrates the proper order for releasing multiple resources. Even if an error occurs, all resources are released in reverse order of acquisition.
The example shows how Temporary Directory Context Manager
temp_directory.py
import tempfile
import shutil
import os
class TemporaryDirectory:
def __enter__(self):
self.dirname = tempfile.mkdtemp()
print(f"Created temp directory: {self.dirname}")
return self.dirname
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Removing temp directory: {self.dirname}")
shutil.rmtree(self.dirname)
return False # Don't suppress exceptions
with TemporaryDirectory() as tempdir:
print(f"Working in: {tempdir}")
with open(os.path.join(tempdir, 'test.txt'), 'w') as f:
f.write('Temporary content')
This context manager creates a temporary directory on entry and removes it on exit, regardless of whether an exception occurred during operations.
The example demonstrates how Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |