Писал ли свой контекстный менеджер
Python
Middle
Без компании
Писал ли свой контекстный менеджер
Ответы
Да, писал. Контекстные менеджеры в Python реализуются через протокол `__enter__` и `__exit__`. Они полезны для управления ресурсами (файлы, соединения и т.д.), гарантируя их освобождение даже при возникновении исключений.
Пример простого контекстного менеджера для работы с файлом:
```
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# Использование
with FileManager('test.txt', 'w') as f:
f.write('Hello, world!')
```
Также можно использовать `contextlib.contextmanager` для создания контекстного менеджера через генератор:
```
from contextlib import contextmanager
@contextmanager
def file_manager(filename, mode):
file = open(filename, mode)
try:
yield file
finally:
file.close()
with file_manager('test.txt', 'w') as f:
f.write('Hello again!')
```