forked from UWPCE-PythonCert/IntroPython2016a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_managers.py
More file actions
53 lines (45 loc) · 1.26 KB
/
Copy pathcontext_managers.py
File metadata and controls
53 lines (45 loc) · 1.26 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
# -*- coding: utf-8 -*-
import sys
from io import StringIO
from contextlib import contextmanager
class Context(object):
"""from Doug Hellmann, PyMOTW
http://pymotw.com/2/contextlib/#module-contextlib
"""
def __init__(self, handle_error):
print('__init__({})'.format(handle_error))
self.handle_error = handle_error
def __enter__(self):
print('__enter__()')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__({}, {}, {})'.format(exc_type, exc_val, exc_tb))
if exc_type == ZeroDivisionError:
return True
else:
return False
# return self.handle_error
@contextmanager
def context(boolean):
print("__init__ code here")
try:
print("__enter__ code goes here")
yield object()
except Exception as e:
print("errors handled here")
if not boolean:
raise e
finally:
print("__exit__ cleanup goes here")
@contextmanager
def print_encoded(encoding):
old_stdout = sys.stdout
sys.stdout = buff = StringIO()
try:
yield None
finally:
sys.stdout = old_stdout
buff.seek(0)
raw = buff.read()
encoded = raw.encode(encoding)
print(encoded)