-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLecture 9.py
86 lines (62 loc) · 1.45 KB
/
Lecture 9.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
82
83
84
85
86
9. Resources Management
-----------------------
# number.txt:
# 1 2 3 5435 22 , sihfskfjes
def some():
file = open('./numbers.txt', 'r')
content = file.read_all()
num_strs = content.split(' ')
nums = []
for num_str in num_strs:
nums.append(int(num_str))
file.close()
def something_else():
while True:
some()
- Not hold the resource more than it's needed
def some():
file = open('./numbers.txt', 'r')
content = file.read_all()
file.close()
num_strs = content.split(' ')
nums = []
for num_str in num_strs:
nums.append(int(num_str))
- OOP constructors and destructors
- RAII - Resource Aquisition is Instantiation
- Monads
class FileResource:
def __init__(self, file_path):
self.__file = None
try:
self.__file = open(file_path)
except Exception as ex:
self.__file = None
def __del__(self):
if (self.__file == None):
pass
else:
self.__file.close()
def read_all(self):
...
def some():
resource = FileResource('./numbers.txt')
contents = resource.read_all()
num_strs = content.split(' ')
nums = []
for num_str in num_strs:
nums.append(int(num_str))
return nums
def something_else():
nums = some()
Problems:
* Double freeing
* Race conditions
* Exceptions
Resource:
* Files
* Memory
* Thread
def some():
with open('./numbers.txt') as file:
contents = file.read_all()