I found in the docs how to merge two PDF file with
merge_pdf_files for which two different context managers are defined. How would this principle generalize for an undefined number of files to merge?
As you can see in the function signature,
*files, there is an asterisk before
files, this means you can use an arbitrary number of files as input.
Handling multiple context managers can be done by using an
ExitStack: contextlib — Utilities for with-statement contexts — Python 3.7.12 documentation
In code this could look something like the snippet below:
def download_merged_pdfs(params, **kwargs) -> DownloadResult: from contextlib import ExitStack files = 10 * [File.from_path(Path(__file__).parent / "dummy.pdf")] with ExitStack() as stack: merged = merge_pdf_files(*[stack.enter_context(f.open_binary()) for f in files]) return DownloadResult(file_content=merged, file_name="merged.pdf")
Thanks Raoul, this is exactly what I was looking for!