Overview
This refactoring will be implemented after PR #37 is merged, as it builds upon the ExitStack pattern introduced there.
Current Implementation
Both send_video and send_pic functions currently manage file handles manually when sending media files.
Issues with Current Approach
- Manual file handle management is error-prone
- If an error occurs while opening files, only some files might be tracked for cleanup
- More complex code with separate lists for files and media groups
Proposed Solution
Use ExitStack from contextlib for safer and cleaner file handling in both functions:
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(file, 'rb')) for file in media_files]
media_group = [InputMediaVideo(file) for file in files] # or InputMediaPhoto for send_pic
await update.message.chat.send_media_group(...)
Benefits
- Automatic Resource Management: ExitStack ensures all files are properly closed
- Cleaner Code: Eliminates manual tracking of opened files
- Exception Safety: Guarantees cleanup in all scenarios
- Reduced Complexity: Handles cleanup logic internally in a more Pythonic way
Implementation Notes
- Add
from contextlib import ExitStack import where needed
- Replace current file handling logic with ExitStack-based implementation in both functions
- Update error handling to work with the new approach
Related PR: #37
Overview
This refactoring will be implemented after PR #37 is merged, as it builds upon the ExitStack pattern introduced there.
Current Implementation
Both
send_videoandsend_picfunctions currently manage file handles manually when sending media files.Issues with Current Approach
Proposed Solution
Use
ExitStackfromcontextlibfor safer and cleaner file handling in both functions:Benefits
Implementation Notes
from contextlib import ExitStackimport where neededRelated PR: #37