This module introduces deterministic cleanup in Python through context managers.
- Difficulty: Advanced.
- Estimated Time: 45-60 minutes.
- Prerequisites:
01-foundations/scope-and-lifetime-basics,03-advanced/structs-and-classes. - Cross-Language Lens: Contrast deterministic cleanup in C++ with
IDisposable,defer, and context-manager style resource handling.
python example/main.py- Automatic cleanup with
with. - Implementing
__enter__and__exit__. - Guarding methods after a resource has been released.
- Distinguishing garbage collection from deterministic scope cleanup.
- Assuming cleanup will happen at a predictable time without a context manager.
- Forgetting to release resources on early returns.
- Reusing an object after it has already been closed.
- Using
__del__as the primary cleanup strategy.
- Python maps this idea to context managers,
try/finally, and explicitclosemethods rather than destructor-based RAII. - Compared with C++, object lifetime and resource cleanup are related but not identical concerns.
- The learner goal is to make release points obvious and reliable.
- exercises/01.py: owned integer buffer with deterministic cleanup.
- exercises/02.py: scope guard that proves nested cleanup order.
- exercises/01.py
- Input: integer
n, thennintegers. - Output: sum and reversed sequence.
- Edge cases:
n <= 0; invalid integer input.
- exercises/02.py
- Input: none.
- Output: enter/exit logs proving automatic cleanup.
- Edge cases: nested scopes; final active counter must return to zero.
- I can explain why
withgives deterministic cleanup. - I can write a small context manager.
- I can prevent work on a closed resource.
- I completed exercises/01.py.
- I completed exercises/02.py.