Skip to content

Commit ebcc27e

Browse files
variable name change and other comments handling
1 parent 0da954c commit ebcc27e

File tree

10 files changed

+75
-85
lines changed

10 files changed

+75
-85
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: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1127,14 +1127,14 @@ def update_page_form_field_values(
11271127
if PG.ANNOTS not in page:
11281128
logger_warning("No fields to update on this page", __name__)
11291129
return
1130-
for annotation in page[PG.ANNOTS]: # type: ignore
1131-
annotation_obj = cast(DictionaryObject, annotation.get_object())
1132-
if annotation_obj.get("/Subtype", "") != "/Widget":
1130+
for annotation_ref in page[PG.ANNOTS]: # type: ignore
1131+
annotation = cast(DictionaryObject, annotation_ref.get_object())
1132+
if annotation.get("/Subtype", "") != "/Widget":
11331133
continue
1134-
if "/FT" in annotation_obj and "/T" in annotation_obj:
1135-
parent_annotation = annotation_obj
1134+
if "/FT" in annotation and "/T" in annotation:
1135+
parent_annotation = annotation
11361136
else:
1137-
parent_annotation = annotation_obj.get(
1137+
parent_annotation = annotation.get(
11381138
PG.PARENT, DictionaryObject()
11391139
).get_object()
11401140

@@ -1150,32 +1150,32 @@ def update_page_form_field_values(
11501150
):
11511151
del parent_annotation["/I"]
11521152
if flags:
1153-
annotation_obj[NameObject(FA.Ff)] = NumberObject(flags)
1153+
annotation[NameObject(FA.Ff)] = NumberObject(flags)
11541154
if not (value is None and flatten): # Only change values if given by user and not flattening.
11551155
if isinstance(value, list):
11561156
lst = ArrayObject(TextStringObject(v) for v in value)
11571157
parent_annotation[NameObject(FA.V)] = lst
11581158
elif isinstance(value, tuple):
1159-
annotation_obj[NameObject(FA.V)] = TextStringObject(
1159+
annotation[NameObject(FA.V)] = TextStringObject(
11601160
value[0],
11611161
)
11621162
else:
11631163
parent_annotation[NameObject(FA.V)] = TextStringObject(value)
11641164
if parent_annotation.get(FA.FT) == "/Btn":
11651165
# Checkbox button (no /FT found in Radio widgets)
11661166
v = NameObject(value)
1167-
ap = cast(DictionaryObject, annotation_obj[NameObject(AA.AP)])
1167+
ap = cast(DictionaryObject, annotation[NameObject(AA.AP)])
11681168
normal_ap = cast(DictionaryObject, ap["/N"])
11691169
if v not in normal_ap:
11701170
v = NameObject("/Off")
11711171
appearance_stream_obj = normal_ap.get(v)
11721172
# other cases will be updated through the for loop
1173-
annotation_obj[NameObject(AA.AS)] = v
1174-
annotation_obj[NameObject(FA.V)] = v
1173+
annotation[NameObject(AA.AS)] = v
1174+
annotation[NameObject(FA.V)] = v
11751175
if flatten and appearance_stream_obj is not None:
11761176
# We basically copy the entire appearance stream, which should be an XObject that
11771177
# is already registered. No need to add font resources.
1178-
rct = cast(RectangleObject, annotation_obj[AA.Rect])
1178+
rct = cast(RectangleObject, annotation[AA.Rect])
11791179
self._add_apstream_object(page, appearance_stream_obj, field, rct[0], rct[1])
11801180
elif (
11811181
parent_annotation.get(FA.FT) == "/Tx"
@@ -1184,12 +1184,12 @@ def update_page_form_field_values(
11841184
# textbox
11851185
if isinstance(value, tuple):
11861186
self._update_field_annotation(
1187-
page, parent_annotation, annotation_obj, value[1], value[2], flatten=flatten
1187+
page, parent_annotation, annotation, value[1], value[2], flatten=flatten
11881188
)
11891189
else:
1190-
self._update_field_annotation(page, parent_annotation, annotation_obj, flatten=flatten)
1190+
self._update_field_annotation(page, parent_annotation, annotation, flatten=flatten)
11911191
elif (
1192-
annotation_obj.get(FA.FT) == "/Sig"
1192+
annotation.get(FA.FT) == "/Sig"
11931193
): # deprecated # not implemented yet
11941194
logger_warning("Signature forms not implemented yet", __name__)
11951195

@@ -1228,19 +1228,19 @@ def reattach_fields(
12281228
if "/Annots" not in page:
12291229
return lst
12301230
annotations = cast(ArrayObject, page["/Annots"])
1231-
for idx, annotation in enumerate(annotations):
1232-
is_indirect = isinstance(annotation, IndirectObject)
1233-
annotation_obj = cast(DictionaryObject, annotation.get_object())
1234-
if annotation_obj.get("/Subtype", "") == "/Widget" and "/FT" in annotation_obj:
1231+
for idx, annotation_ref in enumerate(annotations):
1232+
is_indirect = isinstance(annotation_ref, IndirectObject)
1233+
annotation = cast(DictionaryObject, annotation_ref.get_object())
1234+
if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation:
12351235
if (
1236-
"indirect_reference" in annotation_obj.__dict__
1237-
and annotation_obj.indirect_reference in fields
1236+
"indirect_reference" in annotation.__dict__
1237+
and annotation.indirect_reference in fields
12381238
):
12391239
continue
12401240
if not is_indirect:
1241-
annotations[idx] = self._add_object(annotation_obj)
1242-
fields.append(annotation_obj.indirect_reference)
1243-
lst.append(annotation_obj)
1241+
annotations[idx] = self._add_object(annotation)
1242+
fields.append(annotation.indirect_reference)
1243+
lst.append(annotation)
12441244
return lst
12451245

12461246
def clone_reader_document_root(self, reader: PdfReader) -> None:
@@ -1600,11 +1600,10 @@ def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]
16001600
if obj is not None:
16011601
object_positions.append(stream.tell())
16021602
stream.write(f"{idnum} 0 obj\n".encode())
1603+
object_to_write = obj
16031604
if self._encryption and obj != self._encrypt_entry:
1604-
obj_to_write = self._encryption.encrypt_object(obj, idnum, 0)
1605-
else:
1606-
obj_to_write = obj
1607-
obj_to_write.write_to_stream(stream)
1605+
object_to_write = self._encryption.encrypt_object(obj, idnum, 0)
1606+
object_to_write.write_to_stream(stream)
16081607
stream.write(b"\nendobj\n")
16091608
else:
16101609
object_positions.append(-1)
@@ -1693,10 +1692,7 @@ def add_metadata(self, infos: dict[str, Any]) -> None:
16931692
if isinstance(infos, PdfObject):
16941693
infos = cast(DictionaryObject, infos.get_object())
16951694
for key, value in list(infos.items()):
1696-
if isinstance(value, PdfObject):
1697-
value_obj = value.get_object()
1698-
else:
1699-
value_obj = value
1695+
value_obj = value.get_object() if isinstance(value, PdfObject) else value
17001696
args[NameObject(key)] = create_string_object(str(value_obj))
17011697
if self._info is None:
17021698
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)