Item 12: Nested with Statement

class Resource(object):
    def __init__(self, id):
        assert id in (0, 1, 3, 4), "Bad ID"
        self.id = id
    def __enter__(self):
        print('Acquire', self)
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        print('Release', self)
    def __str__(self):
        return 'resource_' + str(self.id)

for i in range(3):
    print('----')
    try:
        with Resource(2 * i) as a, Resource(2 * i + 1) as b:
            print('Processing:', a, b)
    except AssertionError as e:
        print('Caught:', e)