-
Notifications
You must be signed in to change notification settings - Fork 0
/
Try.py
75 lines (54 loc) · 1.6 KB
/
Try.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
class Try(object):
def __init__(self, action):
self.action = action
self.result = None
self.failedDueToTheRightException = False
def inCaseOf(self, exceptionType):
if self.failedDueToTheRightException or self.result:
return self
try:
self.result = self.action if not callable(self.action) else self.action()
except Exception as err:
if isinstance(err, exceptionType):
self.failedDueToTheRightException = True
return self
return self
def then(self, operation):
if self.result:
return self
if self.failedDueToTheRightException:
self.result = operation() if callable(operation) else operation
return self
else:
return self
@property
def getResult(self):
return self.result
if __name__ == '__main__':
def then():
return 5 / 0
def thenFix():
return 1
def sleep():
import time
time.sleep(5)
return "thenne"
def read():
rdr = open("xxx.xxx", "rb")
return rdr
print("Test #1")
assert (
Try(read)
.inCaseOf(ZeroDivisionError)
.then(thenFix)
.inCaseOf(FileNotFoundError)
.then(sleep)
).getResult == "thenne"
print("Test #2")
assert (
Try(then)
.inCaseOf(ZeroDivisionError)
.then("hello")
.inCaseOf(FileNotFoundError)
.then(sleep)
).getResult == "hello"