-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathcontext.py
More file actions
42 lines (34 loc) · 993 Bytes
/
context.py
File metadata and controls
42 lines (34 loc) · 993 Bytes
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
#!/usr/bin/env python3
"""
Utilities for manging context.
"""
from . import ic # noqa: F401
class _empty_context(object):
"""
A dummy context manager.
"""
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, *args): # noqa: U100
pass
class _state_context(object):
"""
Temporarily modify attribute(s) for an arbitrary object.
"""
def __init__(self, obj, **kwargs):
self._obj = obj
self._attrs_new = kwargs
self._attrs_prev = {
key: getattr(obj, key) for key in kwargs if hasattr(obj, key)
}
def __enter__(self):
for key, value in self._attrs_new.items():
setattr(self._obj, key, value)
def __exit__(self, *args): # noqa: U100
for key in self._attrs_new.keys():
if key in self._attrs_prev:
setattr(self._obj, key, self._attrs_prev[key])
else:
delattr(self._obj, key)