Overview
Guarantee setup and cleanup around a block of code — the same protocol that makes "with open(...)" close files for you.
- __enter__ runs when the block starts
- __exit__ always runs when it ends, even on errors
- Returning True from __exit__ swallows the exception
Short Course
with calls __enter__ before the block and __exit__ after it, whether
the block finished or raised. __exit__ receives the error, if any; returning
True tells Python it was handled.
class Announce:
def __enter__(self):
print("start")
return self
def __exit__(self, exc_type, exc, tb):
print("end") # runs even if the block fails
return False # don't hide errors
with Announce():
print("working") # start / working / end
Task
Write a class ignore_errors(*exceptions) for use with with: any listed
exception raised in the block is silently ignored; any other exception still
propagates.
Test Suites
Pending
Stdout