Skip to content

Commit b1bee72

Browse files
variable name change and other comments handling
1 parent 6da4f06 commit b1bee72

File tree

10 files changed

+64
-89
lines changed

10 files changed

+64
-89
lines changed

pypdf/_cmap.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -460,11 +460,11 @@ def build_font_width_map(
460460
# will consider width of char as avg(width)
461461
m = 0
462462
cpt = 0
463-
for xx in w:
464-
xx_val = xx.get_object()
465-
if xx_val > 0:
466-
m += xx_val
467-
cpt += 1
463+
for xx in w:
464+
xx_value = xx.get_object()
465+
if xx_value > 0:
466+
m += xx_value
467+
cpt += 1
468468
font_width_map["default"] = m / max(1, cpt)
469469
st = cast(int, ft["/FirstChar"])
470470
en = cast(int, ft["/LastChar"])

pypdf/_doc_common.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -391,8 +391,8 @@ def recursive_call(
391391
return top, -1
392392
return None, mi + ma
393393
for idx, kid in enumerate(cast(ArrayObject, node["/Kids"])):
394-
kid_obj = cast(DictionaryObject, kid.get_object())
395-
n, i = recursive_call(kid_obj, mi)
394+
kid_object = cast(DictionaryObject, kid.get_object())
395+
n, i = recursive_call(kid_object, mi)
396396
if n is not None: # page has just been found ...
397397
if i < 0: # ... just below!
398398
return node, idx
@@ -612,8 +612,8 @@ def _build_field(
612612
states: list[str] = []
613613
retval[key][NameObject("/_States_")] = ArrayObject(states)
614614
for k in obj.get(FA.Kids, {}):
615-
k_obj = k.get_object()
616-
for s in list(k_obj["/AP"]["/N"].keys()):
615+
k_object = k.get_object()
616+
for s in list(k_object["/AP"]["/N"].keys()):
617617
if s not in states:
618618
states.append(s)
619619
retval[key][NameObject("/_States_")] = ArrayObject(states)
@@ -641,8 +641,8 @@ def _check_kids(
641641
if PagesAttributes.KIDS in tree:
642642
# recurse down the tree
643643
for kid in tree[PagesAttributes.KIDS]: # type: ignore
644-
kid_obj = kid.get_object()
645-
self.get_fields(kid_obj, retval, fileobj, stack)
644+
kid_object = kid.get_object()
645+
self.get_fields(kid_object, retval, fileobj, stack)
646646

647647
def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None:
648648
field_attributes_tuple = FA.attributes()
@@ -771,16 +771,16 @@ def _get_inherited(obj: DictionaryObject, key: str) -> Any:
771771
else:
772772
kids = field.get("/Kids", ())
773773
for k in kids:
774-
k_obj = k.get_object()
775-
if (k_obj.get("/Subtype", "") == "/Widget") and ("/T" not in k_obj):
774+
k_object = k.get_object()
775+
if (k_object.get("/Subtype", "") == "/Widget") and ("/T" not in k_object):
776776
# Kid that is just a widget, not a field:
777-
if "/P" in k_obj:
778-
ret += [k_obj["/P"].get_object()]
777+
if "/P" in k_object:
778+
ret += [k_object["/P"].get_object()]
779779
else:
780780
ret += [
781781
p
782782
for p in self.pages
783-
if k_obj.indirect_reference in p.get("/Annots", "")
783+
if k_object.indirect_reference in p.get("/Annots", "")
784784
]
785785
return [
786786
x
@@ -1317,9 +1317,9 @@ def xfa(self) -> Optional[dict[str, Any]]:
13171317
i = iter(fields)
13181318
for f in i:
13191319
tag = f
1320-
f_val = next(i)
1321-
if isinstance(f_val, IndirectObject):
1322-
field = cast(Optional[EncodedStreamObject], f_val.get_object())
1320+
field_value = next(i)
1321+
if isinstance(field_value, IndirectObject):
1322+
field = cast(Optional[EncodedStreamObject], field_value.get_object())
13231323
if field:
13241324
es = zlib.decompress(field._data)
13251325
retval[tag] = es

pypdf/_page.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,6 @@ def _get_inline_images(self) -> dict[str, ImageFile]:
739739
for k, v in ii["settings"].items():
740740
if k in {"/Length", "/L"}: # no length is expected
741741
continue
742-
value_for_init: Any
743742
if isinstance(v, list):
744743
value_for_init = ArrayObject(
745744
[self._translate_value_inline_image(k, x) for x in v]
@@ -1232,13 +1231,13 @@ def _merge_page_writer(
12321231
else:
12331232
trsf = Transformation(ctm)
12341233
for a in cast(ArrayObject, page2[PG.ANNOTS]):
1235-
a_obj = a.get_object()
1236-
aa = a_obj.clone(
1234+
annotation_object = a.get_object()
1235+
aa = annotation_object.clone(
12371236
pdf,
12381237
ignore_fields=("/P", "/StructParent", "/Parent"),
12391238
force_duplicate=True,
12401239
)
1241-
r = cast(ArrayObject, a_obj["/Rect"])
1240+
r = cast(ArrayObject, annotation_object["/Rect"])
12421241
pt1 = trsf.apply_on((r[0], r[1]), True)
12431242
pt2 = trsf.apply_on((r[2], r[3]), True)
12441243
aa[NameObject("/Rect")] = ArrayObject(
@@ -1249,8 +1248,8 @@ def _merge_page_writer(
12491248
max(pt1[1], pt2[1]),
12501249
)
12511250
)
1252-
if "/QuadPoints" in a_obj:
1253-
q = cast(ArrayObject, a_obj["/QuadPoints"])
1251+
if "/QuadPoints" in annotation_object:
1252+
q = cast(ArrayObject, annotation_object["/QuadPoints"])
12541253
aa[NameObject("/QuadPoints")] = ArrayObject(
12551254
trsf.apply_on((q[0], q[1]), True)
12561255
+ trsf.apply_on((q[2], q[3]), True)

pypdf/_text_extraction/_layout_mode/_fixed_width_page.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,16 +186,13 @@ def recurs_to_target_op(
186186
tj_ops.append(text_state_mgr.text_state_params(operands[2]))
187187
elif op in (b"Td", b"Tm", b"TD", b"T*"):
188188
text_state_mgr.reset_trm()
189+
operands_for_tm = operands
189190
if op == b"Tm":
190191
text_state_mgr.reset_tm()
191-
operands_for_tm = operands
192192
elif op == b"TD":
193193
text_state_mgr.set_state_param(b"TL", -operands[1])
194-
operands_for_tm = operands
195194
elif op == b"T*":
196195
operands_for_tm = [0, -text_state_mgr.TL]
197-
else:
198-
operands_for_tm = operands
199196
text_state_mgr.add_tm(operands_for_tm)
200197
elif op == b"Tf":
201198
text_state_mgr.set_font(fonts[operands[0]], operands[1])

pypdf/_text_extraction/_layout_mode/_font.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,9 @@ def __post_init__(self) -> None:
6464
for d_font_idx, d_font in enumerate(
6565
self.font_dictionary["/DescendantFonts"]
6666
):
67-
d_font_val = d_font
68-
while isinstance(d_font_val, IndirectObject):
69-
d_font_val = d_font_val.get_object()
70-
self.font_dictionary["/DescendantFonts"][d_font_idx] = d_font_val
67+
d_font_object = d_font.get_object()
68+
assert not isinstance(d_font_object, IndirectObject), d_font_object
69+
self.font_dictionary["/DescendantFonts"][d_font_idx] = d_font_object
7170
ord_map = {
7271
ord(_target): _surrogate
7372
for _target, _surrogate in self.char_map.items()
@@ -81,18 +80,18 @@ def __post_init__(self) -> None:
8180
skip_count = 0
8281
_w = d_font.get("/W", [])
8382
for idx, w_entry in enumerate(_w):
84-
w_val = w_entry.get_object()
83+
w_value = w_entry.get_object()
8584
if skip_count:
8685
skip_count -= 1
8786
continue
88-
if not isinstance(w_val, (int, float)): # pragma: no cover
87+
if not isinstance(w_value, (int, float)): # pragma: no cover
8988
# We should never get here due to skip_count above. Add a
9089
# warning and or use reader's "strict" to force an ex???
9190
continue
9291
# check for format (1): `int [int int int int ...]`
9392
w_next_entry = _w[idx + 1].get_object()
9493
if isinstance(w_next_entry, Sequence):
95-
start_idx, width_list = w_val, w_next_entry
94+
start_idx, width_list = w_value, w_next_entry
9695
self.width_map.update(
9796
{
9897
ord_map[_cidx]: _width
@@ -113,7 +112,7 @@ def __post_init__(self) -> None:
113112
_w[idx + 2].get_object(), (int, float)
114113
):
115114
start_idx, stop_idx, const_width = (
116-
w_val,
115+
w_value,
117116
w_next_entry,
118117
_w[idx + 2].get_object(),
119118
)

pypdf/_writer.py

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,28 +1036,13 @@ def update_page_form_field_values(
10361036
parent_annotation.get(FA.FT) == "/Tx"
10371037
or parent_annotation.get(FA.FT) == "/Ch"
10381038
):
1039-
# Textbox; we need to generate the appearance stream object
1039+
# Textbox; update appearance via helper
10401040
if isinstance(value, tuple):
1041-
appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1042-
acro_form, parent_annotation, annotation, value[1], value[2]
1041+
self._update_field_annotation(
1042+
page, parent_annotation, annotation, value[1], value[2], flatten=flatten
10431043
)
10441044
else:
1045-
appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1046-
acro_form, parent_annotation, annotation
1047-
)
1048-
# Add the appearance stream object
1049-
if AA.AP not in annotation:
1050-
annotation[NameObject(AA.AP)] = DictionaryObject(
1051-
{NameObject("/N"): self._add_object(appearance_stream_obj)}
1052-
)
1053-
elif "/N" not in (ap := cast(DictionaryObject, annotation[AA.AP])):
1054-
cast(DictionaryObject, annotation[NameObject(AA.AP)])[
1055-
NameObject("/N")
1056-
] = self._add_object(appearance_stream_obj)
1057-
else: # [/AP][/N] exists
1058-
n = annotation[AA.AP]["/N"].indirect_reference.idnum # type: ignore
1059-
self._objects[n - 1] = appearance_stream_obj
1060-
appearance_stream_obj.indirect_reference = IndirectObject(n, 0, self)
1045+
self._update_field_annotation(page, parent_annotation, annotation, flatten=flatten)
10611046
elif (
10621047
annotation.get(FA.FT) == "/Sig"
10631048
): # deprecated # not implemented yet
@@ -1100,19 +1085,19 @@ def reattach_fields(
11001085
if "/Annots" not in page:
11011086
return lst
11021087
annotations = cast(ArrayObject, page["/Annots"])
1103-
for idx, annotation in enumerate(annotations):
1104-
is_indirect = isinstance(annotation, IndirectObject)
1105-
annotation_obj = cast(DictionaryObject, annotation.get_object())
1106-
if annotation_obj.get("/Subtype", "") == "/Widget" and "/FT" in annotation_obj:
1088+
for idx, annotation_ref in enumerate(annotations):
1089+
is_indirect = isinstance(annotation_ref, IndirectObject)
1090+
annotation = cast(DictionaryObject, annotation_ref.get_object())
1091+
if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation:
11071092
if (
1108-
"indirect_reference" in annotation_obj.__dict__
1109-
and annotation_obj.indirect_reference in fields
1093+
"indirect_reference" in annotation.__dict__
1094+
and annotation.indirect_reference in fields
11101095
):
11111096
continue
11121097
if not is_indirect:
1113-
annotations[idx] = self._add_object(annotation_obj)
1114-
fields.append(annotation_obj.indirect_reference)
1115-
lst.append(annotation_obj)
1098+
annotations[idx] = self._add_object(annotation)
1099+
fields.append(annotation.indirect_reference)
1100+
lst.append(annotation)
11161101
return lst
11171102

11181103
def clone_reader_document_root(self, reader: PdfReader) -> None:
@@ -1472,11 +1457,10 @@ def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]
14721457
if obj is not None:
14731458
object_positions.append(stream.tell())
14741459
stream.write(f"{idnum} 0 obj\n".encode())
1460+
object_to_write = obj
14751461
if self._encryption and obj != self._encrypt_entry:
1476-
obj_to_write = self._encryption.encrypt_object(obj, idnum, 0)
1477-
else:
1478-
obj_to_write = obj
1479-
obj_to_write.write_to_stream(stream)
1462+
object_to_write = self._encryption.encrypt_object(obj, idnum, 0)
1463+
object_to_write.write_to_stream(stream)
14801464
stream.write(b"\nendobj\n")
14811465
else:
14821466
object_positions.append(-1)
@@ -1565,10 +1549,7 @@ def add_metadata(self, infos: dict[str, Any]) -> None:
15651549
if isinstance(infos, PdfObject):
15661550
infos = cast(DictionaryObject, infos.get_object())
15671551
for key, value in list(infos.items()):
1568-
if isinstance(value, PdfObject):
1569-
value_obj = value.get_object()
1570-
else:
1571-
value_obj = value
1552+
value_obj = value.get_object() if isinstance(value, PdfObject) else value
15721553
args[NameObject(key)] = create_string_object(str(value_obj))
15731554
if self._info is None:
15741555
self._info = DictionaryObject()

pypdf/filters.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -759,12 +759,10 @@ def decode_stream_data(stream: Any) -> bytes:
759759
# If there is no data to decode, we should not try to decode it.
760760
if not data:
761761
return data
762-
for filter_name, params in zip(filters, decode_parms):
763-
params_typed: Optional[DictionaryObject]
764-
if isinstance(params, NullObject):
765-
params_typed = None
766-
else:
767-
params_typed = cast(Optional[DictionaryObject], params)
762+
for filter_name, params_untyped in zip(filters, decode_parms):
763+
params_typed: Optional[DictionaryObject] = None
764+
if not isinstance(params_untyped, NullObject):
765+
params_typed = cast(Optional[DictionaryObject], params_untyped)
768766
if filter_name in (FT.ASCII_HEX_DECODE, FTA.AHx):
769767
data = ASCIIHexDecode.decode(data)
770768
elif filter_name in (FT.ASCII_85_DECODE, FTA.A85):
@@ -785,7 +783,7 @@ def decode_stream_data(stream: Any) -> bytes:
785783
elif filter_name == FT.JBIG2_DECODE:
786784
data = JBIG2Decode.decode(data, params_typed)
787785
elif filter_name == "/Crypt":
788-
if "/Name" in params or "/Type" in params:
786+
if "/Name" in params_untyped or "/Type" in params_untyped:
789787
raise NotImplementedError(
790788
"/Crypt filter with /Name or /Type not supported yet"
791789
)

pypdf/generic/_files.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,8 @@ def _load(cls, catalog: DictionaryObject) -> Generator[EmbeddedFile]:
394394
for kid in cast(ArrayObject, container["/Kids"].get_object()):
395395
# There might be further (nested) kids here.
396396
# Wait for an example before evaluating an implementation.
397-
kid_obj = kid.get_object()
398-
if "/Names" in kid_obj:
399-
yield from cls._load_from_names(cast(ArrayObject, kid_obj["/Names"]))
397+
kid_object = kid.get_object()
398+
if "/Names" in kid_object:
399+
yield from cls._load_from_names(cast(ArrayObject, kid_object["/Names"]))
400400
if "/Names" in container:
401401
yield from cls._load_from_names(cast(ArrayObject, container["/Names"]))

tests/scripts/test_make_release.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def test_get_git_commits_since_tag():
4444
with open(COMMITS__VERSION_4_0_1, mode="rb") as commits_fh, mock.patch(
4545
"urllib.request.urlopen", side_effect=lambda _: commits_fh
4646
), mock.patch("subprocess.check_output", return_value=GIT_LOG__VERSION_4_0_1):
47-
commits_list = make_release.get_git_commits_since_tag("4.0.1")
48-
assert commits_list == [
47+
commits = make_release.get_git_commits_since_tag("4.0.1")
48+
assert commits == [
4949
make_release.Change(
5050
commit_hash="b7bfd0d7eddfd0865a94cc9e7027df6596242cf7",
5151
prefix="BUG",
@@ -87,8 +87,8 @@ def test_get_git_commits_since_tag():
8787
def test_get_formatted_changes():
8888
make_release = pytest.importorskip("make_release")
8989

90-
with open(COMMITS__VERSION_4_0_1, mode="rb") as commits, mock.patch(
91-
"urllib.request.urlopen", side_effect=lambda _: commits
90+
with open(COMMITS__VERSION_4_0_1, mode="rb") as commits_fh, mock.patch(
91+
"urllib.request.urlopen", side_effect=lambda _: commits_fh
9292
), mock.patch("subprocess.check_output", return_value=GIT_LOG__VERSION_4_0_1):
9393
output, output_with_user = make_release.get_formatted_changes("4.0.1")
9494

@@ -182,3 +182,4 @@ def test_get_formatted_changes__other():
182182
- FIX: Broken test due to expired test file URL (#2468) by @pubpub-zz
183183
"""
184184
)
185+

tests/test_images.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ def open_image(path: Union[Path, Image.Image, BytesIO]) -> Image.Image:
3232
else:
3333
if isinstance(path, Path):
3434
assert path.exists()
35-
with Image.open(path) as img_opened:
35+
with Image.open(path) as opened_img:
3636
img = (
37-
img_opened.copy()
37+
opened_img.copy()
3838
) # Opened image should be copied to avoid issues with file closing
3939
return img
4040

0 commit comments

Comments
 (0)