-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_manager_app.py
More file actions
63 lines (42 loc) · 1.46 KB
/
context_manager_app.py
File metadata and controls
63 lines (42 loc) · 1.46 KB
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
# -*- coding: utf-8 -*-
"""
Simple study related to context-manager
1. define a class with an __enter__ and __exit__ method.
2. __enter__ is the before method and can return the value you catch with the as clause
3. __exit__ is the after method and accepts three arguments (exception_type, exception_instance, traceback).
It can return True to suppress exceptions that occur with block.
4. __init__ should be used to catch arguments to your context-manager (filename to open, etc)
"""
from contextlib import contextmanager
# First Example
class MyContextManager(object):
# def print_msg(self, msg):
# print(msg)
def __init__(self):
print("__init__")
# before stuff
def __enter__(self):
print("__enter__")
return self
def __exit__(self, exc_type, value, traceback):
print(exc_type, value, traceback)
# Second Example
@contextmanager
def file_open(path, mode = 'w'):
try:
file_obj = open(path, mode)
yield file_obj
except OSError:
print('Error')
finally:
print('Closing File')
file_obj.close()
if __name__ == "__main__":
# with MyContextManager() as test:
# test.print_msg("Using context manager")
# # raise ValueError
with file_open('test.txt') as fo:
fo.write('Context Managers')
with file_open('test.txt') as fo:
content = fo.read()
print(content)