Context ManagersBeginner
1Question 1 of 1
pythonHow do Context Managers and the 'with' statement manage resources in Python?
Explanation & Concept
Context managers guarantee that resources (file descriptors, database connections, locks) are safely acquired and released, even if an unhandled exception occurs.
You create them by implementing `__enter__` and `__exit__`, or using the `@contextmanager` generator decorator from `contextlib`.
Code Example
python
from contextlib import contextmanager
@contextmanager
def managed_database_session():
print("Opening database session...")
session = {"connected": True}
try:
yield session # Hand control over to the with-block
finally:
print("Safely closing database session.")
session["connected"] = False
with managed_database_session() as db:
print("Performing queries on db...")
# Even if an error happens here, the finally block still closes the session!How It Works & Key Takeaways
Context managers eliminate resource leaks by making clean-up deterministic, replacing boilerplate `try...finally` structures.
Mock Test · 1 Questions · Optional
Ready for *args & **kwargs?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions