Skip to content

Commit 4793888

Browse files
author
krsm
committed
adding context manager study
1 parent d7a4cb1 commit 4793888

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

context_manager_app.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,57 @@
66
77
2. __enter__ is the before method and can return the value you catch with the as clause
88
9-
3. __exit__ is the after method and accepts three arguments (excpetion_type, execption_instance, traceback).
10-
It can return True to supress exceptions that occur with block.
9+
3. __exit__ is the after method and accepts three arguments (exception_type, exception_instance, traceback).
10+
It can return True to suppress exceptions that occur with block.
1111
12-
4. __init__ shoud be used to catch arguments to your context-manager (filename to open, etc)
12+
4. __init__ should be used to catch arguments to your context-manager (filename to open, etc)
1313
1414
"""
1515

16-
class ContextManager(object):
16+
from contextlib import contextmanager
17+
18+
# First Example
19+
class MyContextManager(object):
20+
21+
# def print_msg(self, msg):
22+
# print(msg)
1723

1824
def __init__(self):
19-
print ("__init__")
25+
print("__init__")
2026

2127
#before stuff
2228
def __enter__(self):
2329
print("__enter__")
30+
return self
31+
32+
def __exit__(self, exc_type, value, traceback):
33+
print(exc_type, value, traceback)
34+
2435

25-
def __exit__ (self, type, value, traceback):
26-
print()
36+
37+
# Second Example
38+
@contextmanager
39+
def file_open(path, mode = 'w'):
40+
try:
41+
file_obj = open(path, mode)
42+
yield file_obj
43+
except OSError:
44+
print('Error')
45+
finally:
46+
print('Closing File')
47+
file_obj.close()
2748

2849

2950
if __name__ == "__main__":
3051

31-
pass
52+
# with MyContextManager() as test:
53+
# test.print_msg("Using context manager")
54+
# # raise ValueError
55+
56+
with file_open('test.txt') as fo:
57+
fo.write('Context Managers')
58+
59+
with file_open('test.txt') as fo:
60+
content = fo.read()
61+
62+
print(content)

0 commit comments

Comments
 (0)