Some jobs have a beginning and an end that must both happen: open a file and close it, take a lock and release it, start a transaction and commit it. Forgetting the end, especially when an error interrupts the middle, is a classic source of bugs. The with statement is Python’s answer. In this lesson you see what it does step by step, and write your own objects that work with it.
More lessons in Complete Python Programming