Skip to content

Commit f805e6d

Browse files
authored
DEV: Remove ignore Ruff rule RET505 (#3210)
RET505: Unnecessary "else" after "return" statement.
1 parent fda2c9b commit f805e6d

File tree

14 files changed

+160
-197
lines changed

14 files changed

+160
-197
lines changed

pypdf/_cmap.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,7 @@ def _parse_to_unicode(
211211
if "/ToUnicode" not in ft:
212212
if ft.get("/Subtype", "") == "/Type1":
213213
return _type1_alternative(ft, map_dict, int_entry)
214-
else:
215-
return {}, []
214+
return {}, []
216215
process_rg: bool = False
217216
process_char: bool = False
218217
multiline_rg: Union[

pypdf/_doc_common.py

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -352,11 +352,10 @@ def get_num_pages(self) -> int:
352352
# the original method (flattened page count) is used.
353353
if self.is_encrypted:
354354
return self.root_object["/Pages"]["/Count"] # type: ignore
355-
else:
356-
if self.flattened_pages is None:
357-
self._flatten(self._readonly)
358-
assert self.flattened_pages is not None
359-
return len(self.flattened_pages)
355+
if self.flattened_pages is None:
356+
self._flatten(self._readonly)
357+
assert self.flattened_pages is not None
358+
return len(self.flattened_pages)
360359

361360
def get_page(self, page_number: int) -> PageObject:
362361
"""
@@ -585,16 +584,15 @@ def get_fields(
585584
def _get_qualified_field_name(self, parent: DictionaryObject) -> str:
586585
if "/TM" in parent:
587586
return cast(str, parent["/TM"])
588-
elif "/Parent" in parent:
587+
if "/Parent" in parent:
589588
return (
590589
self._get_qualified_field_name(
591590
cast(DictionaryObject, parent["/Parent"])
592591
)
593592
+ "."
594593
+ cast(str, parent.get("/T", ""))
595594
)
596-
else:
597-
return cast(str, parent.get("/T", ""))
595+
return cast(str, parent.get("/T", ""))
598596

599597
def _build_field(
600598
self,
@@ -713,12 +711,11 @@ def get_form_text_fields(self, full_qualified_name: bool = False) -> Dict[str, A
713711
def indexed_key(k: str, fields: Dict[Any, Any]) -> str:
714712
if k not in fields:
715713
return k
716-
else:
717-
return (
718-
k
719-
+ "."
720-
+ str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2)
721-
)
714+
return (
715+
k
716+
+ "."
717+
+ str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2)
718+
)
722719

723720
# Retrieve document form fields
724721
formfields = self.get_fields()
@@ -759,12 +756,11 @@ def get_pages_showing_field(
759756
def _get_inherited(obj: DictionaryObject, key: str) -> Any:
760757
if key in obj:
761758
return obj[key]
762-
elif "/Parent" in obj:
759+
if "/Parent" in obj:
763760
return _get_inherited(
764761
cast(DictionaryObject, obj["/Parent"].get_object()), key
765762
)
766-
else:
767-
return None
763+
return None
768764

769765
try:
770766
# to cope with all types
@@ -824,7 +820,7 @@ def open_destination(
824820
oa = oa.decode()
825821
if isinstance(oa, str):
826822
return create_string_object(oa)
827-
elif isinstance(oa, ArrayObject):
823+
if isinstance(oa, ArrayObject):
828824
try:
829825
page, typ, *array = oa
830826
fit = Fit(typ, tuple(array))
@@ -907,8 +903,7 @@ def threads(self) -> Optional[ArrayObject]:
907903
catalog = self.root_object
908904
if CO.THREADS in catalog:
909905
return cast("ArrayObject", catalog[CO.THREADS])
910-
else:
911-
return None
906+
return None
912907

913908
@abstractmethod
914909
def _get_page_number_by_indirect(
@@ -961,18 +956,17 @@ def _build_destination(
961956
):
962957
page = NullObject()
963958
return Destination(title, page, Fit.fit())
964-
else:
965-
page, typ, *array = array # type: ignore
966-
try:
967-
return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore
968-
except PdfReadError:
969-
logger_warning(f"Unknown destination: {title} {array}", __name__)
970-
if self.strict:
971-
raise
972-
# create a link to first Page
973-
tmp = self.pages[0].indirect_reference
974-
indirect_reference = NullObject() if tmp is None else tmp
975-
return Destination(title, indirect_reference, Fit.fit())
959+
page, typ, *array = array # type: ignore
960+
try:
961+
return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore
962+
except PdfReadError:
963+
logger_warning(f"Unknown destination: {title} {array}", __name__)
964+
if self.strict:
965+
raise
966+
# create a link to first Page
967+
tmp = self.pages[0].indirect_reference
968+
indirect_reference = NullObject() if tmp is None else tmp
969+
return Destination(title, indirect_reference, Fit.fit())
976970

977971
def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]:
978972
dest, title, outline_item = None, None, None

pypdf/_page.py

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -603,8 +603,7 @@ def _get_ids_image(
603603
_i = getattr(obj, "indirect_reference", None)
604604
if _i in call_stack:
605605
return []
606-
else:
607-
call_stack.append(_i)
606+
call_stack.append(_i)
608607
if self.inline_images is None:
609608
self.inline_images = self._get_inline_images()
610609
if obj is None:
@@ -663,9 +662,9 @@ def _get_image(
663662
image=imgd[2],
664663
indirect_reference=xobjs[id].indirect_reference,
665664
)
666-
else: # in a sub object
667-
ids = id[1:]
668-
return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]]))
665+
# in a sub object
666+
ids = id[1:]
667+
return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]]))
669668

670669
@property
671670
def images(self) -> VirtualListImages:
@@ -1028,10 +1027,8 @@ def _get_contents_as_bytes(self) -> Optional[bytes]:
10281027
obj = self[PG.CONTENTS].get_object()
10291028
if isinstance(obj, list):
10301029
return b"".join(x.get_object().get_data() for x in obj)
1031-
else:
1032-
return cast(EncodedStreamObject, obj).get_data()
1033-
else:
1034-
return None
1030+
return cast(EncodedStreamObject, obj).get_data()
1031+
return None
10351032

10361033
def get_contents(self) -> Optional[ContentStream]:
10371034
"""
@@ -1050,10 +1047,8 @@ def get_contents(self) -> Optional[ContentStream]:
10501047
obj = self[PG.CONTENTS].get_object()
10511048
if isinstance(obj, NullObject):
10521049
return None
1053-
else:
1054-
return ContentStream(obj, pdf)
1055-
else:
1056-
return None
1050+
return ContentStream(obj, pdf)
1051+
return None
10571052

10581053
def replace_contents(
10591054
self, content: Union[None, ContentStream, EncodedStreamObject, ArrayObject]
@@ -1081,13 +1076,12 @@ def replace_contents(
10811076
if is_null_or_none(content):
10821077
if PG.CONTENTS not in self:
10831078
return
1084-
else:
1085-
assert self.indirect_reference is not None
1086-
assert self[PG.CONTENTS].indirect_reference is not None
1087-
self.indirect_reference.pdf._objects[
1088-
self[PG.CONTENTS].indirect_reference.idnum - 1 # type: ignore
1089-
] = NullObject()
1090-
del self[PG.CONTENTS]
1079+
assert self.indirect_reference is not None
1080+
assert self[PG.CONTENTS].indirect_reference is not None
1081+
self.indirect_reference.pdf._objects[
1082+
self[PG.CONTENTS].indirect_reference.idnum - 1 # type: ignore
1083+
] = NullObject()
1084+
del self[PG.CONTENTS]
10911085
elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"):
10921086
try:
10931087
self[NameObject(PG.CONTENTS)] = self.indirect_reference.pdf._add_object(
@@ -1693,12 +1687,11 @@ def page_number(self) -> Optional[int]:
16931687
"""
16941688
if self.indirect_reference is None:
16951689
return None
1696-
else:
1697-
try:
1698-
lst = self.indirect_reference.pdf.pages
1699-
return lst.index(self)
1700-
except ValueError:
1701-
return None
1690+
try:
1691+
lst = self.indirect_reference.pdf.pages
1692+
return lst.index(self)
1693+
except ValueError:
1694+
return None
17021695

17031696
def _debug_for_extract(self) -> str: # pragma: no cover
17041697
out = ""
@@ -2472,8 +2465,7 @@ def _get_fonts(self) -> Tuple[Set[str], Set[str]]:
24722465
def annotations(self) -> Optional[ArrayObject]:
24732466
if "/Annots" not in self:
24742467
return None
2475-
else:
2476-
return cast(ArrayObject, self["/Annots"])
2468+
return cast(ArrayObject, self["/Annots"])
24772469

24782470
@annotations.setter
24792471
def annotations(self, value: Optional[ArrayObject]) -> None:

pypdf/_page_labels.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,5 +285,4 @@ def nums_next(
285285
i = nums.index(key) + 2
286286
if i < len(nums):
287287
return (nums[i], nums[i + 1])
288-
else:
289-
return (None, None)
288+
return (None, None)

pypdf/_text_extraction/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,11 @@ def mult(m: List[float], n: List[float]) -> List[float]:
7979
def orient(m: List[float]) -> int:
8080
if m[3] > 1e-6:
8181
return 0
82-
elif m[3] < -1e-6:
82+
if m[3] < -1e-6:
8383
return 180
84-
elif m[1] > 0:
84+
if m[1] > 0:
8585
return 90
86-
else:
87-
return 270
86+
return 270
8887

8988

9089
def crlf_space_check(

pypdf/_utils.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -472,12 +472,11 @@ def rename_kwargs(
472472
def _human_readable_bytes(bytes: int) -> str:
473473
if bytes < 10**3:
474474
return f"{bytes} Byte"
475-
elif bytes < 10**6:
475+
if bytes < 10**6:
476476
return f"{bytes / 10**3:.1f} kB"
477-
elif bytes < 10**9:
477+
if bytes < 10**9:
478478
return f"{bytes / 10**6:.1f} MB"
479-
else:
480-
return f"{bytes / 10**9:.1f} GB"
479+
return f"{bytes / 10**9:.1f} GB"
481480

482481

483482
# The following class has been copied from Django:
@@ -594,12 +593,12 @@ def __lt__(self, other: Any) -> bool:
594593

595594
if self_value < other_value:
596595
return True
597-
elif self_value > other_value:
596+
if self_value > other_value:
598597
return False
599598

600599
if self_suffix < other_suffix:
601600
return True
602-
elif self_suffix > other_suffix:
601+
if self_suffix > other_suffix:
603602
return False
604603

605604
return len(self.components) < len(other.components)

pypdf/_writer.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -599,8 +599,7 @@ def insert_page(
599599
raise ValueError("Invalid index value")
600600
if index >= len(self.flattened_pages):
601601
return self.add_page(page, excluded_keys)
602-
else:
603-
return self._add_page(page, index, excluded_keys)
602+
return self._add_page(page, index, excluded_keys)
604603

605604
def _get_page_number_by_indirect(
606605
self, indirect_reference: Union[None, int, NullObject, IndirectObject]
@@ -1962,8 +1961,7 @@ def add_named_destination_array(
19621961
named_dest.insert(i, destination)
19631962
named_dest.insert(i, TextStringObject(title))
19641963
return
1965-
else:
1966-
i += 2
1964+
i += 2
19671965
named_dest.extend([TextStringObject(title), destination])
19681966
return
19691967

@@ -2923,7 +2921,7 @@ def _get_cloned_page(
29232921
) -> Optional[IndirectObject]:
29242922
if isinstance(page, NullObject):
29252923
return None
2926-
elif isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page":
2924+
if isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page":
29272925
_i = page.indirect_reference
29282926
elif isinstance(page, IndirectObject):
29292927
_i = page
@@ -3094,7 +3092,7 @@ def find_outline_item(
30943092
or o.get("/Title", None) == outline_item
30953093
):
30963094
return [i]
3097-
elif "/First" in o:
3095+
if "/First" in o:
30983096
res = self.find_outline_item(
30993097
outline_item, cast(OutlineType, o["/First"])
31003098
)
@@ -3301,19 +3299,17 @@ def _pdf_objectify(obj: Union[Dict[str, Any], str, float, List[Any]]) -> PdfObje
33013299
for key, value in obj.items():
33023300
to_add[NameObject(key)] = _pdf_objectify(value)
33033301
return to_add
3304-
elif isinstance(obj, str):
3302+
if isinstance(obj, str):
33053303
if obj.startswith("/"):
33063304
return NameObject(obj)
3307-
else:
3308-
return TextStringObject(obj)
3309-
elif isinstance(obj, (float, int)):
3305+
return TextStringObject(obj)
3306+
if isinstance(obj, (float, int)):
33103307
return FloatObject(obj)
3311-
elif isinstance(obj, list):
3308+
if isinstance(obj, list):
33123309
return ArrayObject(_pdf_objectify(i) for i in obj)
3313-
else:
3314-
raise NotImplementedError(
3315-
f"{type(obj)=} could not be cast to a PdfObject"
3316-
)
3310+
raise NotImplementedError(
3311+
f"{type(obj)=} could not be cast to a PdfObject"
3312+
)
33173313

33183314

33193315
def _create_outline_item(

0 commit comments

Comments
 (0)