-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_context_manager.py
More file actions
36 lines (25 loc) · 873 Bytes
/
Copy path14_context_manager.py
File metadata and controls
36 lines (25 loc) · 873 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
# Context managers: __enter__/__exit__ are what "with" calls.
class Timer:
def __enter__(self):
import time
self.start = time.monotonic()
# whatever __enter__ returns becomes the "as" variable
return self
def __exit__(self, exc_type, exc_value, traceback):
import time
self.elapsed = time.monotonic() - self.start
print(f"took {self.elapsed:.4f}s")
# returning True here would SWALLOW the exception; False re-raises
return False
with Timer():
sum(range(1_000_000))
# The same thing with far less code — contextlib turns a generator into
# a context manager: everything before yield is __enter__, after is __exit__.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
yield
print(f"</{name}>")
with tag("h1"):
print("Hello")