Code

Enter and Exit

You've used with open(...) as f:. The file closes itself afterwards, even if an error happens. That's a context manager, and you can build your own.

A context manager is any object with two methods:

  • __enter__(self) runs at the start of the with block. Whatever it returns is bound to the name after as.
  • __exit__(self, exc_type, exc, tb) runs at the end, always, even if the block raised an exception. If there was an error, the three arguments describe it; otherwise they are all None.
class Shout:
    def __enter__(self):
        print("BEGIN")
        return self

    def __exit__(self, exc_type, exc, tb):
        print("END")
        return False   # don't hide errors

with Shout() as s:
    print("inside")
# BEGIN / inside / END

If __exit__ returns True, the exception is swallowed. Returning False (or None) lets it carry on. Hiding errors by accident is a nasty bug, so only return True on purpose.

Assignment

Finish the Torch class. Torch(name, log) takes a name and a list to write into.

  1. __enter__ appends "light <name>" to log and returns the torch itself.
  2. __exit__ appends "snuff <name>" to log and returns False, so errors still propagate.