This repository has been archived by the owner on Aug 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeywords-with.py
81 lines (61 loc) · 2.22 KB
/
keywords-with.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from contextlib import contextmanager
import sys
# --------------------------------------------------
address = sys.path[0] + "/keywords-raise.py"
# --------------------------------------------------
# "open" is a "ContextManager"
# "with" makes the exception handeling easy
with open(address, "r") as file:
print("\n".join(file.readlines()))
# --------------------------------------------------
# Alternative to "with" for "open"
file = open(address, "r")
try:
print("\n".join(file.readlines()))
finally:
file.close()
# --------------------------------------------------
@contextmanager
def my_context_manager(name): # Useless example; just for test
name = name.upper()
yield name
with my_context_manager("hello") as name:
print(name)
# --------------------------------------------------
@contextmanager
def my_div_context_manager(a, b): # Useless example; just for test
try:
yield a / b
except:
yield "Bad Input"
with my_div_context_manager(10, 0) as result:
print(result)
# --------------------------------------------------
class MyMath(object): # Useless example; just for test
def __init__(self):
print("\nMyMath.__init__")
def __enter__(self):
print("MyMath.__enter__")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("MyMath.__exit__", exc_type, exc_value, traceback)
return self
def __del__(self):
print("MyMath.__del__")
def div(self, a, b):
return a / b
with MyMath() as math:
print(math.div(10, 10))
print(math.div(20, 10))
print(math.div(0, 10))
print(math.div(10, 0)) # error
print(math.div(10, 10)) # Not called
print(math.div(20, 10)) # Not called
print(math.div(30, 10)) # Not called
print("End of program")
## Read more from here:
# https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for
# https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit
# https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
# https://stackoverflow.com/questions/26907175/how-to-manipulate-the-exception-in-exit-of-a-context-manager
# https://www.geeksforgeeks.org/__exit__-in-python/