
Python
Create custom context managers and understand exception handling in with blocks.
from contextlib import contextmanager
@contextmanager
def open_and_lock_file(filename):
"""Custom context manager with cleanup"""
file = open(filename, "r")
# Acquire resource
try:
yield file
finally:
# Release resource
file.close()
# Usage
with open_and_lock_file("data.txt") as f:
content = f.read()
# File guaranteed to close@contextmanager
def managed_transaction(db):
"""Transaction context manager"""
try:
yield db
db.commit() # Success
except Exception:
db.rollback() # Error
raise
# All-or-nothing operation
with managed_transaction(db) as transaction:
transaction.insert("users", data)Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward