1class ProtectedSection:
2 def __init__(self, log=(), suppress=()):
3 self.log_exceptions = log
4 self.suppress_exceptions = suppress
5 self.exception = None
6
7 def __enter__(self):
8 return self
9
10 def __exit__(self, exception_type, exception_value, traceback):
11 if exception_type is not None:
12 if issubclass(exception_type, self.log_exceptions):
13 self.exception = exception_value
14 return True
15 elif issubclass(exception_type, self.suppress_exceptions):
16 return True
17 return False
.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)
| f | 1 | class ProtectedSection: | f | 1 | class ProtectedSection: |
| 2 | def __init__(self, log=(), suppress=()): | 2 | def __init__(self, log=(), suppress=()): | ||
| 3 | self.log_exceptions = log | 3 | self.log_exceptions = log | ||
| 4 | self.suppress_exceptions = suppress | 4 | self.suppress_exceptions = suppress | ||
| 5 | self.exception = None | 5 | self.exception = None | ||
| 6 | 6 | ||||
| 7 | def __enter__(self): | 7 | def __enter__(self): | ||
| 8 | return self | 8 | return self | ||
| 9 | 9 | ||||
| 10 | def __exit__(self, exception_type, exception_value, traceback): | 10 | def __exit__(self, exception_type, exception_value, traceback): | ||
| 11 | if exception_type is not None: | 11 | if exception_type is not None: | ||
| 12 | if issubclass(exception_type, self.log_exceptions): | 12 | if issubclass(exception_type, self.log_exceptions): | ||
| 13 | self.exception = exception_value | 13 | self.exception = exception_value | ||
| 14 | return True | 14 | return True | ||
| 15 | elif issubclass(exception_type, self.suppress_exceptions): | 15 | elif issubclass(exception_type, self.suppress_exceptions): | ||
| 16 | return True | 16 | return True | ||
| 17 | return False | 17 | return False | ||
| 18 | 18 | ||||
| n | 19 | with ProtectedSection(log=(ZeroDivisionError, IndexError)) as err: | n | ||
| 20 | x = 1 / 0 | ||||
| 21 | 19 | ||||
| n | 22 | print(err.exception) | n | ||
| 23 | 20 | ||||
| t | t | 21 |
| Legends | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||
09.11.2024 11:43