1# test with when context manager raises in __enter__/__exit__ 2 3class CtxMgr: 4 def __init__(self, id): 5 self.id = id 6 7 def __enter__(self): 8 print("__enter__", self.id) 9 if 10 <= self.id < 20: 10 raise Exception('enter', self.id) 11 return self 12 13 def __exit__(self, a, b, c): 14 print("__exit__", self.id, repr(a), repr(b)) 15 if 15 <= self.id < 25: 16 raise Exception('exit', self.id) 17 18# no raising 19try: 20 with CtxMgr(1): 21 pass 22except Exception as e: 23 print(e) 24 25# raise in enter 26try: 27 with CtxMgr(10): 28 pass 29except Exception as e: 30 print(e) 31 32# raise in enter and exit 33try: 34 with CtxMgr(15): 35 pass 36except Exception as e: 37 print(e) 38 39# raise in exit 40try: 41 with CtxMgr(20): 42 pass 43except Exception as e: 44 print(e) 45