`Document.delete_pages()` raises `ValueError: bad page number(s)` on negative page numbers passed as two positional arguments
Description of the bug
Description of the bug *
Document.delete_pages() supports negative page indexing to delete pages relative to the end of the document.
Negative indices are correctly wrapped using while p < 0: p += page_count for keyword arguments (lines 4431–4434):
while f < 0: f += page_count
while t < 0: t += page_count
And for a single integer argument (lines 4452–4453):
while pno < 0: pno += page_count
However, in the two positional argument branch (if len(args) == 2: on lines 4441–4450), negative index normalization is completely omitted. Calling doc.delete_pages(-2, -1) generates negative page numbers in numbers = (-2, -1), which then triggers the sanity check at line 4463 (if numbers[0] < 0: raise ValueError("bad page number(s)")).
Meanwhile, doc.delete_pages(from_page=-2, to_page=-1) and doc.delete_pages(-1) work as expected.
How to reproduce the bug
Highlight in Code
src/__init__.py:4441-4450:
4441: if len(args) == 2:
4442: f, t = args
4443: if not (type(f) is int and type(t) is int):
4444: raise ValueError("both arguments must be int")
4445: >>>>> # BUG: Missing 'while f < 0: f += page_count' and 'while t < 0: t += page_count'
4446: if f > t:
4447: f, t = t, f
4448: if not f <= t < page_count:
4449: raise ValueError("bad page number(s)")
4450: numbers = tuple(range(f, t + 1))
Steps & Reproduction Code
import pymupdf
doc = pymupdf.open()
for _ in range(5):
doc.new_page()
# Case A: Keyword arguments (works correctly)
doc.delete_pages(from_page=-2, to_page=-1)
print("Keyword deletion succeeded, remaining pages:", doc.page_count) # 3
# Reset document
doc = pymupdf.open()
for _ in range(5):
doc.new_page()
# Case B: Positional arguments (fails unexpectedly)
try:
doc.delete_pages(-2, -1)
except ValueError as e:
print("Positional deletion failed:", e)
# Output: ValueError: bad page number(s)
Expected Behavior
doc.delete_pages(-2, -1) should normalize negative indices to valid page indices (e.g. 3, 4 for a 5-page document) and succeed, consistent with keyword arguments and single-page deletion.
Actual Behavior
Raises ValueError: bad page number(s).
Suggested Fix
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -4444,6 +4444,10 @@ class Document:
raise ValueError("both arguments must be int")
+ while f < 0:
+ f += page_count
+ while t < 0:
+ t += page_count
if f > t:
f, t = t, f
if not f <= t < page_count:
PyMuPDF version
2.1
Operating system
Windows
Python version
3.14
Thanks for your submission. We will add the fix in one of next versions.