|
6 | 6 |
|
7 | 7 | 2. __enter__ is the before method and can return the value you catch with the as clause
|
8 | 8 |
|
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. |
11 | 11 |
|
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) |
13 | 13 |
|
14 | 14 | """
|
15 | 15 |
|
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) |
17 | 23 |
|
18 | 24 | def __init__(self):
|
19 |
| - print ("__init__") |
| 25 | + print("__init__") |
20 | 26 |
|
21 | 27 | #before stuff
|
22 | 28 | def __enter__(self):
|
23 | 29 | print("__enter__")
|
| 30 | + return self |
| 31 | + |
| 32 | + def __exit__(self, exc_type, value, traceback): |
| 33 | + print(exc_type, value, traceback) |
| 34 | + |
24 | 35 |
|
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() |
27 | 48 |
|
28 | 49 |
|
29 | 50 | if __name__ == "__main__":
|
30 | 51 |
|
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