
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 thewithblock. Whatever it returns is bound to the name afteras.__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 allNone.
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.
__enter__appends"light <name>"tologand returns the torch itself.__exit__appends"snuff <name>"tologand returnsFalse, so errors still propagate.
Finish the Torch class. Torch(name, log) takes a name and a list to write into.
__enter__appends"light <name>"tologand returns the torch itself.__exit__appends"snuff <name>"tologand returnsFalse, so errors still propagate.
main.py Python sleeping
Press Run to try your code, then Check to test it.