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_val, exc_tb):
11
12 if exc_type in self.log:
13 self.exception = exc_val
14 return True
15
16 if exc_type in self.suppress:
17 return True
18
19
20
.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 = log | 3 | self.log = log | ||
| 4 | self.suppress = suppress | 4 | self.suppress = 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,exc_type, exc_val, exc_tb): | 10 | def __exit__(self,exc_type, exc_val, exc_tb): | ||
| 11 | 11 | ||||
| 12 | if exc_type in self.log: | 12 | if exc_type in self.log: | ||
| 13 | self.exception = exc_val | 13 | self.exception = exc_val | ||
| 14 | return True | 14 | return True | ||
| 15 | 15 | ||||
| 16 | if exc_type in self.suppress: | 16 | if exc_type in self.suppress: | ||
| 17 | return True | 17 | return True | ||
| 18 | 18 | ||||
| 19 | 19 | ||||
| 20 | 20 | ||||
| 21 | 21 | ||||
| 22 | 22 | ||||
| n | 23 | with ProtectedSection(log=(ZeroDivisionError, IndexError)) as err: | n | ||
| 24 | x = 1 / 0 | ||||
| 25 | 23 | ||||
| t | 26 | print(err.exception) | t | ||
| 27 | # division by zero | ||||
| 28 | print(type(err.exception)) | ||||
| 29 | # <class 'ZeroDivisionError'> | ||||
| 30 | |||||
| 31 | with ProtectedSection(suppress=(ZeroDivisionError, IndexError)) as err: | ||||
| 32 | x = 1 / 0 | ||||
| 33 | |||||
| 34 | print(err.exception) | ||||
| 35 | # None | ||||
| 36 | |||||
| 37 | with ProtectedSection(log=(ZeroDivisionError, IndexError), suppress=(TypeError, ZeroDivisionError, Exception)) as err: | ||||
| 38 | x = 1 / 0 | ||||
| 39 | |||||
| 40 | print(err.exception) | ||||
| 41 | # division by zero | ||||
| 42 | print(type(err.exception)) | ||||
| 43 | # <class 'ZeroDivisionError'> |
| Legends | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||