Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions pypdf/_doc_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
import struct
from abc import abstractmethod
from collections.abc import Generator, Iterable, Iterator, Mapping
Expand Down Expand Up @@ -1045,10 +1046,8 @@ def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]:
node.get("/Count", 0) >= 0
)
outline_item.node = node
try:
with contextlib.suppress(AttributeError):
outline_item.indirect_reference = node.indirect_reference
except AttributeError:
pass
return outline_item

@property
Expand Down
19 changes: 6 additions & 13 deletions pypdf/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
import math
from collections.abc import Iterable, Iterator, Sequence
from copy import deepcopy
Expand Down Expand Up @@ -909,10 +910,8 @@ def compute_unique_key(base_key: str) -> tuple[str, bool]:
if not same_value:
if is_pdf_writer:
new_res[newname] = page2res.raw_get(key).clone(pdf)
try:
with contextlib.suppress(AttributeError):
new_res[newname] = new_res[newname].indirect_reference
except AttributeError:
pass
else:
new_res[newname] = page2res.raw_get(key)
lst = sorted(new_res.items())
Expand Down Expand Up @@ -1021,11 +1020,9 @@ def replace_contents(
if isinstance(self.get(PG.CONTENTS, None), ArrayObject):
content_array = cast(ArrayObject, self[PG.CONTENTS])
for reference in content_array:
try:
# Occurs when called on PdfReader.
with contextlib.suppress(ValueError):
writer._replace_object(indirect_reference=reference.indirect_reference, obj=NullObject())
except ValueError:
# Occurs when called on PdfReader.
pass

if isinstance(content, ArrayObject):
content = ArrayObject(writer._add_object(obj) for obj in content)
Expand Down Expand Up @@ -1272,10 +1269,8 @@ def _merge_page_writer(
+ trsf.apply_on((q[4], q[5]), True)
+ trsf.apply_on((q[6], q[7]), True)
)
try:
with contextlib.suppress(KeyError):
aa["/Popup"][NameObject("/Parent")] = aa.indirect_reference
except KeyError:
pass
try:
aa[NameObject("/P")] = self.indirect_reference
annots.append(aa.indirect_reference)
Expand Down Expand Up @@ -1655,7 +1650,7 @@ def _debug_for_extract(self) -> str: # pragma: no cover
out += enc_repr + "\n"
except Exception:
pass
try:
with contextlib.suppress(Exception):
out += (
self[PG.RESOURCES]["/Font"][fo][ # type:ignore
"/ToUnicode"
Expand All @@ -1664,8 +1659,6 @@ def _debug_for_extract(self) -> str: # pragma: no cover
.decode()
+ "\n"
)
except Exception:
pass

except KeyError:
out += "No Font\n"
Expand Down
9 changes: 3 additions & 6 deletions pypdf/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
import os
import re
import sys
Expand Down Expand Up @@ -893,14 +894,10 @@ def _read_standard_xref_table(self, stream: StreamType) -> None:
else:
if entry_type_b == b"n":
self.xref[generation][num] = offset
try:
with contextlib.suppress(Exception):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

self.xref_free_entry[generation][num] = entry_type_b == b"f"
except Exception:
pass
try:
with contextlib.suppress(Exception):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

self.xref_free_entry[65535][num] = entry_type_b == b"f"
except Exception:
pass
cnt += 1
num += 1
read_non_whitespace(stream)
Expand Down
5 changes: 2 additions & 3 deletions pypdf/_text_extraction/_text_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
import math
from typing import Any, Callable, Optional, Union

Expand Down Expand Up @@ -300,10 +301,8 @@ def _handle_tf(self, operands: list[Any]) -> None:
)

self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space...
try:
with contextlib.suppress(Exception): # keep previous size
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

self.font_size = float(operands[1])
except Exception:
pass # keep previous size

def _handle_td(self, operands: list[Any]) -> float:
"""Handle Td (Move text position) operation - Table 5.5 page 406."""
Expand Down
33 changes: 9 additions & 24 deletions pypdf/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
import decimal
import enum
import hashlib
Expand Down Expand Up @@ -362,10 +363,8 @@ def _info(self) -> Optional[DictionaryObject]:
@_info.setter
def _info(self, value: Optional[Union[IndirectObject, DictionaryObject]]) -> None:
if value is None:
try:
with contextlib.suppress(KeyError, AttributeError):
self._objects[self._info_obj.indirect_reference.idnum - 1] = None # type: ignore
except (KeyError, AttributeError):
pass
self._info_obj = None
else:
if self._info_obj is None:
Expand Down Expand Up @@ -518,12 +517,10 @@ def _add_page(
# page; therefore in order to add multiple copies of the same
# page, we need to create a new dictionary for the page, however the
# objects below (including content) are not duplicated:
try: # delete an already existing page
with contextlib.suppress(Exception): # delete an already existing page
del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore
page_org.indirect_reference.idnum # type: ignore
]
except Exception:
pass

page = cast(
"PageObject", page_org.clone(self, False, excluded_keys).get_object()
Expand Down Expand Up @@ -751,10 +748,8 @@ def open_destination(
@open_destination.setter
def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None:
if dest is None:
try:
with contextlib.suppress(KeyError):
del self._root_object["/OpenAction"]
except KeyError:
pass
elif isinstance(dest, str):
self._root_object[NameObject("/OpenAction")] = TextStringObject(dest)
elif isinstance(dest, Destination):
Expand Down Expand Up @@ -1255,10 +1250,8 @@ def clone_document_from_reader(
)
# else: _info_obj = None done in clone_reader_document_root()

try:
with contextlib.suppress(AttributeError):
self._ID = cast(ArrayObject, reader._ID).clone(self)
except AttributeError:
pass

if callable(after_page_append):
for page in cast(
Expand Down Expand Up @@ -1704,10 +1697,8 @@ def replace_in_obj(
if not is_null_or_none(self._info):
unreferenced[self._info.indirect_reference.idnum - 1] = False # type: ignore

try:
with contextlib.suppress(AttributeError):
unreferenced[self._ID.indirect_reference.idnum - 1] = False # type: ignore
except AttributeError:
pass

for i in compress(range(len(self._objects)), unreferenced):
self._objects[i] = None
Expand Down Expand Up @@ -2156,10 +2147,8 @@ def _remove_objects_from_page__clean_forms(
if k1 not in ["/Length", "/Filter", "/DecodeParms"]
}
)
try:
with contextlib.suppress(AttributeError): # pragma: no cover
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the pragma seems wrong, as this will not report coverage issues with the body.

content.indirect_reference = o.indirect_reference
except AttributeError: # pragma: no cover
pass
stack.append(elt)

# clean subforms
Expand Down Expand Up @@ -3183,15 +3172,11 @@ def reset_translation(
if reader is None:
self._id_translated = {}
elif isinstance(reader, PdfReader):
try:
with contextlib.suppress(Exception):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

del self._id_translated[id(reader)]
except Exception:
pass
elif isinstance(reader, IndirectObject):
try:
with contextlib.suppress(Exception):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

del self._id_translated[id(reader.pdf)]
except Exception:
pass
else:
raise Exception("invalid parameter {reader}")
Comment thread
stefan6419846 marked this conversation as resolved.

Expand Down
5 changes: 2 additions & 3 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
__author__ = "Mathieu Fenniak"
__author_email__ = "biziqe@mathieu.fenniak.net"

import contextlib
import logging
import re
import sys
Expand Down Expand Up @@ -1544,10 +1545,8 @@ def __init__(self, data: DictionaryObject) -> None:
)
self.indirect_reference = data.indirect_reference
for attr in field_attributes:
try:
with contextlib.suppress(KeyError):
self[NameObject(attr)] = data[attr]
except KeyError:
pass
if isinstance(self.get("/V"), EncodedStreamObject):
d = cast(EncodedStreamObject, self[NameObject("/V")]).get_data()
if isinstance(d, bytes):
Expand Down
9 changes: 3 additions & 6 deletions pypdf/generic/_viewerpref.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import contextlib
from typing import (
Any,
Optional,
Expand All @@ -43,10 +44,8 @@ def __init__(self, obj: Optional[DictionaryObject] = None) -> None:
super().__init__(self)
if not is_null_or_none(obj):
self.update(obj.items()) # type: ignore
try:
with contextlib.suppress(AttributeError):
self.indirect_reference = obj.indirect_reference # type: ignore
except AttributeError:
pass

def _get_bool(self, key: str, default: Optional[BooleanObject]) -> Optional[BooleanObject]:
return self.get(key, default)
Expand All @@ -69,10 +68,8 @@ def _get_arr(self, key: str, default: Optional[list[Any]]) -> Optional[ArrayObje

def _set_arr(self, key: str, v: Optional[ArrayObject]) -> None:
if v is None:
try:
with contextlib.suppress(KeyError):
del self[NameObject(key)]
except KeyError:
pass
return
if not isinstance(v, ArrayObject):
raise ValueError("ArrayObject is expected")
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ ignore = [
"RUF002", # Detect confusable Unicode-to-Unicode units. Introduces bugs
"S101", # Use of `assert` detected
"S110", # `try`-`except`-`pass` detected, consider logging the exception
"SIM105", # contextlib.suppress
"SIM108", # Don't enforce ternary operators
"SLF001", # Private member accessed
"TC006", # To discuss: Add quotes to type expression in `typing.cast()`
Expand Down
5 changes: 2 additions & 3 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test the pypdf._reader module."""
import contextlib
import io
import struct
import sys
Expand Down Expand Up @@ -513,10 +514,8 @@ def test_read_malformed_header(caplog):
PdfReader(io.BytesIO(b"foo"), strict=True)
assert exc.value.args[0] == "PDF starts with 'foo', but '%PDF-' expected"
caplog.clear()
try:
with contextlib.suppress(Exception):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we are at it, I suggest tightening the suppressed exceptions here.

PdfReader(io.BytesIO(b"foo"), strict=False)
except Exception:
pass
assert caplog.messages[0].startswith("invalid pdf header")


Expand Down
Loading