Exercise: Suppress and log
Sometimes an error is expected and you want to carry on, but you still want a record of it. A batch job that skips bad rows is one example.
Exercise: finish the context manager suppress_and_log(log, *exc_types).
- If the
withblock raises one ofexc_types(or a subclass of one), swallow it and append"TypeName: message"tolog, like"KeyError: 'missing'". Code after thewithstatement carries on. - Any other exception passes through untouched, and nothing is logged.
- If nothing is raised, nothing is logged.
Hint: in the generator, wrap yield in try. except exc_types as e
works, because except accepts a tuple of types. A class with __exit__
returning True works too.
The standard library has contextlib.suppress, which does the same minus
the log.
Press Check to run the tests.