-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass_ contextmanager.py
61 lines (44 loc) · 1.64 KB
/
class_ contextmanager.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
'''
Декоратор @contextmanager дозволяє нам створити контекстний менеджер за допомогою генератора, та спростити написання коду порівняно з класом FileManager, який використовує методи __enter__ та __exit__.
'''
from contextlib import contextmanager
@contextmanager
def file_manager(filename, mode='w', encoding='utf-8'):
print("Відкриваємо файл", filename)
file = open(filename, mode, encoding=encoding)
try:
yield file
finally:
print("Закриваємо файл", filename)
file.close()
print("Завершення блоку with")
if __name__ == '__main__':
with file_manager('new_file.txt') as f:
f.write('Hello world!\n')
f.write('The end\n')
#=================================================
from contextlib import contextmanager
from datetime import datetime
@contextmanager
def managed_resource(*args, **kwargs):
log = ''
timestamp = datetime.now().timestamp()
msg = f'{timestamp:<20}|{args[0]:^15}| open \n'
log += msg
file_handler = open(*args, **kwargs)
try:
yield file_handler
finally:
diff = datetime.now().timestamp() - timestamp
msg = f'{timestamp:<20}|{args[0]:^15}| closed {round(diff, 6):>15}s \n'
log += msg
file_handler.close()
print(log)
with managed_resource('new_file.txt', 'r') as f:
print(f.read())
'''
Hello world!
The end
1707565076.245372 | new_file.txt | open
1707565076.245372 | new_file.txt | closed 0.004001.
'''