Repository: apache/airflow
File: providers/imap/src/airflow/providers/imap/hooks/imap.py (Python)

Code before:
        if max_mails is not None and max_mails <= 0:
            raise ValueError("max_mails must be a positive integer")

        all_matching_attachments: list[tuple] = []

        self.mail_client.select(mail_folder)

        for mail_id in self._list_mail_ids_desc(mail_filter, max_mails=max_mails):
            response_mail_body = self._fetch_mail_body(mail_id)
            matching_attachments = self._check_mail_body(response_mail_body, name, check_regex, latest_only)

            if matching_attachments:
                all_matching_attachments.extend(matching_attachments)
                if latest_only:
                    break

        self.mail_client.close()

        return all_matching_attachments

    def _list_mail_ids_desc(self, mail_filter: str, max_mails: int | None = None) -> Iterable[str]:
        if not self.mail_client:
            raise RuntimeError("The 'mail_client' should be initialized before!")
        _, data = self.mail_client.search(None, mail_filter)
        mail_ids = data[0].split()
        mail_ids_desc = reversed(mail_ids)

        if max_mails is not None:
            return islice(mail_ids_desc, max_mails)

        return mail_ids_desc

    def _fetch_mail_body(self, mail_id: str) -> str:
        if not self.mail_client:
            raise RuntimeError("The 'mail_client' should be initialized before!")
        _, data = self.mail_client.fetch(mail_id, "(RFC822)")
        mail_body = data[0][1]  # type: ignore # The mail body is always in this specific location
        mail_body_str = mail_body.decode("utf-8")  # type: ignore
        return mail_body_str

    def _check_mail_body(
        self, response_mail_body: str, name: str, check_regex: bool, latest_only: bool
    ) -> list[tuple[Any, Any]]:
        mail = Mail(response_mail_body)
        if mail.has_attachments():
            return mail.get_attachments_by_name(name, check_regex, find_first=latest_only)
        return []

    def _create_files(self, mail_attachments: list, local_output_directory: str) -> None:
        for name, payload in mail_attachments:
            if self._is_symlink(name):

Review comment (performance):
I assume the motivation behind the new argument is for performance. However, this `reversed` call would defeat half of it since the hook would need to spend time ordering entries that are going be end up being dropped anyway.

I would recommend to instead implement logic that calculates the islice arguments _before_ reversing, and then reverse the result afterwards. Using an islice would also be unnecessary in this situation—sorting would impact performance the most; if the number of entires is limited, a simple slice (or using the `[:end]` syntax) would be sufficient.

Code after:
        if max_mails is not None and max_mails <= 0:
            raise ValueError("max_mails must be a positive integer")

        all_matching_attachments: list[tuple] = []

        self.mail_client.select(mail_folder)

        for mail_id in self._list_mail_ids_desc(mail_filter, max_mails=max_mails):
            response_mail_body = self._fetch_mail_body(mail_id)
            matching_attachments = self._check_mail_body(response_mail_body, name, check_regex, latest_only)

            if matching_attachments:
                all_matching_attachments.extend(matching_attachments)
                if latest_only:
                    break

        self.mail_client.close()

        return all_matching_attachments

    def _list_mail_ids_desc(self, mail_filter: str, max_mails: int | None = None) -> Iterable[str]:
        if not self.mail_client:
            raise RuntimeError("The 'mail_client' should be initialized before!")
        _, data = self.mail_client.search(None, mail_filter)
        mail_ids = data[0].split()
        if max_mails is not None:
            mail_ids = mail_ids[-max_mails:]

        return reversed(mail_ids)

    def _fetch_mail_body(self, mail_id: str) -> str:
        if not self.mail_client:
            raise RuntimeError("The 'mail_client' should be initialized before!")
        _, data = self.mail_client.fetch(mail_id, "(RFC822)")
        mail_body = data[0][1]  # type: ignore # The mail body is always in this specific location
        mail_body_str = mail_body.decode("utf-8")  # type: ignore
        return mail_body_str

    def _check_mail_body(
        self, response_mail_body: str, name: str, check_regex: bool, latest_only: bool
    ) -> list[tuple[Any, Any]]:
        mail = Mail(response_mail_body)
        if mail.has_attachments():
            return mail.get_attachments_by_name(name, check_regex, find_first=latest_only)
        return []

    def _create_files(self, mail_attachments: list, local_output_directory: str) -> None:
        for name, payload in mail_attachments:
            if self._is_symlink(name):
                self.log.error("Can not create file because it is a symlink!")
            elif self._is_escaping_current_directory(name):