-
Notifications
You must be signed in to change notification settings - Fork 492
Expand file tree
/
Copy pathcontextmanagers.py
More file actions
37 lines (27 loc) · 838 Bytes
/
contextmanagers.py
File metadata and controls
37 lines (27 loc) · 838 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
#! /usr/bin/env python3
"""Context managers are useful for automatically releasing resources once you are done with them."""
# common context manager that will close
# a file when it has been read
with open('README.md') as f:
contents = f.read()
# make your own context manager
import contextlib
@contextlib.contextmanager
def unlock(resource):
resource.locked = False
try:
yield
finally:
resource.locked = True
# a resource that is locked
class Resource:
def __init__(self):
self.locked = True
resource = Resource()
# test that it is indeed locked
print(resource.locked)
# call your 'unlock' context manager with your resource
with unlock(resource):
print(resource.locked) # check that it is unlocked
# ensure it was re-locked when it left the 'unlock' context
print(resource.locked)