Skip to content

Commit 48cf619

Browse files
variable name change and other comments handling
1 parent 9fca116 commit 48cf619

File tree

10 files changed

+81
-91
lines changed

10 files changed

+81
-91
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: 34 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -978,19 +978,19 @@ def update_page_form_field_values(
978978
if PG.ANNOTS not in page:
979979
logger_warning("No fields to update on this page", __name__)
980980
return
981-
for annotation in page[PG.ANNOTS]: # type: ignore
982-
annotation_obj = cast(DictionaryObject, annotation.get_object())
983-
if annotation_obj.get("/Subtype", "") != "/Widget":
981+
for annotation_ref in page[PG.ANNOTS]: # type: ignore
982+
annotation = cast(DictionaryObject, annotation_ref.get_object())
983+
if annotation.get("/Subtype", "") != "/Widget":
984984
continue
985-
if "/FT" in annotation_obj and "/T" in annotation_obj:
986-
parent_annotation = annotation_obj
985+
if "/FT" in annotation and "/T" in annotation:
986+
parent_annotation = annotation
987987
else:
988-
parent_annotation = annotation_obj.get(
988+
parent_annotation = annotation.get(
989989
PG.PARENT, DictionaryObject()
990990
).get_object()
991991

992992
for field, value in fields.items():
993-
rectangle = cast(RectangleObject, annotation_obj[AA.Rect])
993+
rectangle = cast(RectangleObject, annotation[AA.Rect])
994994
if not (
995995
self._get_qualified_field_name(parent_annotation) == field
996996
or parent_annotation.get("/T", None) == field
@@ -1002,13 +1002,13 @@ def update_page_form_field_values(
10021002
):
10031003
del parent_annotation["/I"]
10041004
if flags:
1005-
annotation_obj[NameObject(FA.Ff)] = NumberObject(flags)
1005+
annotation[NameObject(FA.Ff)] = NumberObject(flags)
10061006
if not (value is None and flatten): # Only change values if given by user and not flattening.
10071007
if isinstance(value, list):
10081008
lst = ArrayObject(TextStringObject(v) for v in value)
10091009
parent_annotation[NameObject(FA.V)] = lst
10101010
elif isinstance(value, tuple):
1011-
annotation_obj[NameObject(FA.V)] = TextStringObject(
1011+
annotation[NameObject(FA.V)] = TextStringObject(
10121012
value[0],
10131013
)
10141014
else:
@@ -1019,18 +1019,18 @@ def update_page_form_field_values(
10191019
# We can find the associated appearance stream object
10201020
# within the annotation.
10211021
v = NameObject(value)
1022-
ap = cast(DictionaryObject, annotation_obj[NameObject(AA.AP)])
1022+
ap = cast(DictionaryObject, annotation[NameObject(AA.AP)])
10231023
normal_ap = cast(DictionaryObject, ap["/N"])
10241024
if v not in normal_ap:
10251025
v = NameObject("/Off")
10261026
appearance_stream_obj = normal_ap.get(v)
10271027
# other cases will be updated through the for loop
1028-
annotation_obj[NameObject(AA.AS)] = v
1029-
annotation_obj[NameObject(FA.V)] = v
1028+
annotation[NameObject(AA.AS)] = v
1029+
annotation[NameObject(FA.V)] = v
10301030
if flatten and appearance_stream_obj is not None:
10311031
# We basically copy the entire appearance stream, which should be an XObject that
10321032
# is already registered. No need to add font resources.
1033-
rct = cast(RectangleObject, annotation_obj[AA.Rect])
1033+
rct = cast(RectangleObject, annotation[AA.Rect])
10341034
self._add_apstream_object(page, appearance_stream_obj, field, rct[0], rct[1])
10351035
elif (
10361036
parent_annotation.get(FA.FT) == "/Tx"
@@ -1039,27 +1039,27 @@ def update_page_form_field_values(
10391039
# Textbox; we need to generate the appearance stream object
10401040
if isinstance(value, tuple):
10411041
appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1042-
acro_form, parent_annotation, annotation_obj, value[1], value[2]
1042+
acro_form, parent_annotation, annotation, value[1], value[2]
10431043
)
10441044
else:
10451045
appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1046-
acro_form, parent_annotation, annotation_obj
1046+
acro_form, parent_annotation, annotation
10471047
)
10481048
# Add the appearance stream object
1049-
if AA.AP not in annotation_obj:
1050-
annotation_obj[NameObject(AA.AP)] = DictionaryObject(
1049+
if AA.AP not in annotation:
1050+
annotation[NameObject(AA.AP)] = DictionaryObject(
10511051
{NameObject("/N"): self._add_object(appearance_stream_obj)}
10521052
)
1053-
elif "/N" not in (ap := cast(DictionaryObject, annotation_obj[AA.AP])):
1054-
cast(DictionaryObject, annotation_obj[NameObject(AA.AP)])[
1053+
elif "/N" not in (ap := cast(DictionaryObject, annotation[AA.AP])):
1054+
cast(DictionaryObject, annotation[NameObject(AA.AP)])[
10551055
NameObject("/N")
10561056
] = self._add_object(appearance_stream_obj)
10571057
else: # [/AP][/N] exists
1058-
n = annotation_obj[AA.AP]["/N"].indirect_reference.idnum # type: ignore
1058+
n = annotation[AA.AP]["/N"].indirect_reference.idnum # type: ignore
10591059
self._objects[n - 1] = appearance_stream_obj
10601060
appearance_stream_obj.indirect_reference = IndirectObject(n, 0, self)
10611061
elif (
1062-
annotation_obj.get(FA.FT) == "/Sig"
1062+
annotation.get(FA.FT) == "/Sig"
10631063
): # deprecated # not implemented yet
10641064
logger_warning("Signature forms not implemented yet", __name__)
10651065
if flatten and appearance_stream_obj is not None:
@@ -1100,19 +1100,19 @@ def reattach_fields(
11001100
if "/Annots" not in page:
11011101
return lst
11021102
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:
1103+
for idx, annotation_ref in enumerate(annotations):
1104+
is_indirect = isinstance(annotation_ref, IndirectObject)
1105+
annotation = cast(DictionaryObject, annotation_ref.get_object())
1106+
if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation:
11071107
if (
1108-
"indirect_reference" in annotation_obj.__dict__
1109-
and annotation_obj.indirect_reference in fields
1108+
"indirect_reference" in annotation.__dict__
1109+
and annotation.indirect_reference in fields
11101110
):
11111111
continue
11121112
if not is_indirect:
1113-
annotations[idx] = self._add_object(annotation_obj)
1114-
fields.append(annotation_obj.indirect_reference)
1115-
lst.append(annotation_obj)
1113+
annotations[idx] = self._add_object(annotation)
1114+
fields.append(annotation.indirect_reference)
1115+
lst.append(annotation)
11161116
return lst
11171117

11181118
def clone_reader_document_root(self, reader: PdfReader) -> None:
@@ -1472,11 +1472,10 @@ def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]
14721472
if obj is not None:
14731473
object_positions.append(stream.tell())
14741474
stream.write(f"{idnum} 0 obj\n".encode())
1475+
object_to_write = obj
14751476
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)
1477+
object_to_write = self._encryption.encrypt_object(obj, idnum, 0)
1478+
object_to_write.write_to_stream(stream)
14801479
stream.write(b"\nendobj\n")
14811480
else:
14821481
object_positions.append(-1)
@@ -1565,10 +1564,7 @@ def add_metadata(self, infos: dict[str, Any]) -> None:
15651564
if isinstance(infos, PdfObject):
15661565
infos = cast(DictionaryObject, infos.get_object())
15671566
for key, value in list(infos.items()):
1568-
if isinstance(value, PdfObject):
1569-
value_obj = value.get_object()
1570-
else:
1571-
value_obj = value
1567+
value_obj = value.get_object() if isinstance(value, PdfObject) else value
15721568
args[NameObject(key)] = create_string_object(str(value_obj))
15731569
if self._info is None:
15741570
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"]))

0 commit comments

Comments
 (0)