forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst-class.py
More file actions
50 lines (38 loc) · 1.11 KB
/
first-class.py
File metadata and controls
50 lines (38 loc) · 1.11 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
import os
verbose = True
class CreateFile:
def __init__(self, path, txt='hello world\n'):
self.path = path
self.txt = txt
def execute(self):
if verbose:
print(f"[creating file '{self.path}']")
with open(self.path, mode='w', encoding='utf-8') as out_file:
out_file.write(self.txt)
def undo(self):
try:
delete_file(self.path)
except:
print('delete action not successful...')
print('... file was probably already deleted.')
def delete_file(path):
if verbose:
print(f"deleting file {path}...")
os.remove(path)
def main():
orig_name = 'file1'
df=delete_file
commands = [CreateFile(orig_name),]
commands.append(df)
for c in commands:
try:
c.execute()
except AttributeError as e:
df(orig_name)
for c in reversed(commands):
try:
c.undo()
except AttributeError as e:
pass
if __name__ == "__main__":
main()