## # Example 1: simulate opening and closing resources after is usage. ## class Operation(object): def __init__(self): print('Initializing...') self.status = 'initial' def __enter__(self): print('Opening...') self.status = 'open' return self def __exit__(self, type, value, traceback): print('Closing...') self.status = 'closed' print('Status: {}'.format(self.status)) # print('Type: {}'.format(type)) # print('Traceback: {}'.format(traceback)) # return True with Operation() as operation: print('Running...') print('Status: {}'.format(operation.status)) # raise NotImplementedError('foo') ## # Example 2: imitate the TestCase.assertRaises() method. ## class UnitTest(object): def assertRaises(self, exception): self.exception = exception return self def __enter__(self): return self.exception def __exit__(self, type, value, traceback): if self.exception == type: print('Exception mached!') return True else: print('Exception not mached or not raised!') return False test = UnitTest() with test.assertRaises(NotImplementedError) as error: raise NotImplementedError with test.assertRaises(NotImplementedError) as error: print('Not raising any exception...') ## # Example 3: try using the contextmanager decorator + generator ## from contextlib import contextmanager class UnitTestPlus(object): @contextmanager def assertRaises(self, exception): try: yield exception print('Exception not mached or not raised!') except exception: print('Exception mached!') test = UnitTestPlus() with test.assertRaises(NotImplementedError) as error: raise NotImplementedError with test.assertRaises(NotImplementedError) as error: print('Not raising any exception...')