-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.py
63 lines (53 loc) · 1.54 KB
/
context.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from contextlib import contextmanager
@contextmanager
def patch(obj, *delattrs, **setattrs):
added = object()
originals = {}
try:
for name in delattrs:
originals[name] = getattr(obj, name)
delattr(obj, name)
for name, value in setattrs.items():
originals[name] = getattr(obj, name, added)
setattr(obj, name, value)
yield
finally:
for name, value in originals.items():
if value is added:
delattr(obj, name)
else:
setattr(obj, name, value)
@contextmanager
def translate_exceptions(exc_types):
"""Re-raise exceptions as different types.
>>> with translate_exceptions({Exception: ValueError}):
... raise Exception('ayy')
Traceback (most recent call last):
...
ValueError: ayy
>>> with translate_exceptions({ValueError: KeyError}):
... raise Exception('nope')
Traceback (most recent call last):
...
Exception: nope
"""
try:
yield
except tuple(exc_types) as exc:
raise exc_types[type(exc)](exc) from exc
@contextmanager
def handle(handlers):
"""Handle the specified exceptions with the given functions.
>>> with handle({Exception: print}):
... raise Exception('ayy')
ayy
>>> with handle({ValueError: print}):
... raise Exception('nope')
Traceback (most recent call last):
...
Exception: nope
"""
try:
yield
except tuple(handlers) as exc:
handlers[type(exc)](exc)