Use a class-based context manager to guarantee cleanup around a block.
What You Will Learn
The with statement calls __enter__ before executing the block and __exit__ afterward, even when an exception occurs. __exit__ receives exception information; returning True suppresses an exception, so ordinary cleanup managers generally return False. Context managers manage resources or temporary state, not only files.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class TemporarySetting:
def __enter__(self):
print("Enable setting")
return self
def __exit__(self, error_type, error, traceback):
print("Restore setting")
return False
with TemporarySetting():
print("Work inside the managed block")
How the Example Works
- The class TemporarySetting groups data and behavior; its methods run when called on an instance.
- The control-flow block demonstrates when each value is processed or when cleanup and exception handling take effect.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
Enable setting
Work inside the managed block
Restore setting
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Raise ValueError inside the with block, catch it outside and confirm cleanup still ran.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Forgetting to restore state when the with block raises an exception.
- Returning True from __exit__ unintentionally and hiding a real program error.
Key Takeaways
- Use a class-based context manager to guarantee cleanup around a block.
- The with statement calls __enter__ before executing the block and __exit__ afterward, even when an exception occurs. __exit__ receives exception information; returning True suppresses an exception, so ordinary cleanup managers generally return False.
- Apply this operation only after checking the assumptions and input conditions shown in the example.