1class ProtectedSection:
2 def __init__(self, log=(), suppress=()):
3 self.log = log
4 self.suppress = suppress
5 self.exception = None
6
7 def __enter__(self):
8 return self
9
10 def __exit__(self, exc_type, exc_value, traceback):
11 if exc_type is None:
12 return False
13
14 if issubclass(exc_type, self.log):
15 self.exception = exc_value
16 return True
17
18 if issubclass(exc_type, self.suppress):
19 return True
20
21 return False
22
23with ProtectedSection(log=(ZeroDivisionError, IndexError)) as err:
24 x = 1 / 0
25
26print(err.exception)
27print(type(err.exception))
28
29with ProtectedSection(suppress=(ZeroDivisionError, IndexError)) as err:
30 x = 1 / 0
31
32print(err.exception)
33
34with ProtectedSection(log=(ZeroDivisionError, IndexError), suppress=(TypeError, ZeroDivisionError, Exception)) as err:
35 x = 1 / 0
36
37print(err.exception)
38print(type(err.exception))
division by zero
<class 'ZeroDivisionError'>
None
division by zero
<class 'ZeroDivisionError'>
.F
======================================================================
FAIL: test_special_cases (test.TestSolution.test_special_cases)
Test special cases to show you that you missed something.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 128, in test_special_cases
self.assertIsNone(cm.exception)
AssertionError: ZeroDivisionError('division by zero') is not None
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
09.11.2024 21:12