Create a synchronous context manager using __enter__() and __exit__().
How It Works
with calls __enter__ on entry and __exit__ on exit even if an exception occurs. __exit__ receives exception details and should normally return False or None to propagate failures.
contextlib.contextmanager is a convenient alternative for simple context managers.
Step-by-Step Example
class ManagedResource:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exception_type, exception_value, traceback_object):
print("Resource released")
return False
with ManagedResource() as resource:
print("Working")
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Resource acquired
Working
Resource released
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create a context manager that records start and end timestamps.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Returning True from __exit__ accidentally and silently suppressing a failure.
- Forgetting that __exit__ must handle cleanup even when the body raises an error.
Key Takeaways
- Create a synchronous context manager using __enter__() and __exit__().
- with calls __enter__ on entry and __exit__ on exit even if an exception occurs.
- contextlib.contextmanager is a convenient alternative for simple context managers.