Skip to content

refactor: Improve file handling in send_video and send_pic using ExitStack #41

@coderabbitai

Description

@coderabbitai

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

  1. Manual file handle management is error-prone
  2. If an error occurs while opening files, only some files might be tracked for cleanup
  3. 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

  1. Automatic Resource Management: ExitStack ensures all files are properly closed
  2. Cleaner Code: Eliminates manual tracking of opened files
  3. Exception Safety: Guarantees cleanup in all scenarios
  4. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions