The with-statement construct can be used with any type of object which implements the context manager protocol. We're not going to show you how to implement a context-manager is this book – for that you'll need to refer to The Python Journeyman – but we will show you a simple way to make your own classes usable in a with statement. Put this code into a the module fridge.py:
# fridge.py
"""Demonstrate raiding a refrigerator."""
class RefrigeratorRaider:
"""Raid a refrigerator."""
def open(self):
print("Open fridge door.")
def take(self, food):
print("Finding {}...".format(food))
if food == 'deep fried pizza':
raise RuntimeError("Health warning!")
print("Taking {}".format(food))
...