Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

STY: Apply fixes suggested by pylint #999

Merged
merged 4 commits into from
Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
More f-strings
  • Loading branch information
MartinThoma committed Jun 16, 2022
commit a38f3a1ef0df6207b0db4915dccc84d4ca83456d
4 changes: 2 additions & 2 deletions PyPDF2/_cmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ def parse_to_unicode(
) # join is here as some cases where the code was split
int_entry.append(int(lst[0], 16))
lst = lst[2:]
for a in map_dict:
if map_dict[a] == " ":
for a, value in map_dict.items():
if value == " ":
space_code = a
return map_dict, space_code, int_entry

Expand Down
4 changes: 1 addition & 3 deletions PyPDF2/_merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,9 +564,7 @@ def _associate_dests_to_pages(self, pages: List[_MergedPage]) -> None:
if pageno is not None:
nd[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError(
"Unresolved named destination '{}'".format(nd["/Title"])
)
raise ValueError(f"Unresolved named destination '{nd['/Title']}'")

def _associate_bookmarks_to_pages(
self, pages: List[_MergedPage], bookmarks: Optional[Iterable[Bookmark]] = None
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ def _content_stream_rename(
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
else:
raise KeyError("type of operands is %s" % type(operands))
raise KeyError(f"type of operands is {type(operands)}")
return stream

@staticmethod
Expand Down
54 changes: 22 additions & 32 deletions PyPDF2/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ def _build_outline(self, node: DictionaryObject) -> Optional[Destination]:
outline = self._namedDests[dest]
outline[NameObject("/Title")] = title # type: ignore
else:
raise PdfReadError("Unexpected destination %r" % dest)
raise PdfReadError(f"Unexpected destination {dest!r}")
return outline

@property
Expand Down Expand Up @@ -993,13 +993,14 @@ def _get_object_from_stream(
# Stream object cannot be read. Normally, a critical error, but
# Adobe Reader doesn't complain, so continue (in strict mode?)
warnings.warn(
"Invalid stream (index %d) within object %d %d: %s"
% (i, indirect_reference.idnum, indirect_reference.generation, exc),
f"Invalid stream (index {i}) within object "
f"{indirect_reference.idnum} {indirect_reference.generation}: "
f"{exc}",
PdfReadWarning,
)

if self.strict:
raise PdfReadError("Can't read object stream: %s" % exc)
raise PdfReadError(f"Can't read object stream: {exc}")
# Replace with null. Hopefully it's nothing important.
obj = NullObject()
return obj
Expand Down Expand Up @@ -1030,26 +1031,18 @@ def get_object(self, indirect_reference: IndirectObject) -> Optional[PdfObject]:
# Xref table probably had bad indexes due to not being zero-indexed
if self.strict:
raise PdfReadError(
"Expected object ID (%d %d) does not match actual (%d %d); xref table not zero-indexed."
% (
indirect_reference.idnum,
indirect_reference.generation,
idnum,
generation,
)
f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) "
f"does not match actual ({idnum} {generation}); "
"xref table not zero-indexed."
)
else:
pass # xref table is corrected in non-strict mode
elif idnum != indirect_reference.idnum and self.strict:
# some other problem
raise PdfReadError(
"Expected object ID (%d %d) does not match actual (%d %d)."
% (
indirect_reference.idnum,
indirect_reference.generation,
idnum,
generation,
)
f"Expected object ID ({indirect_reference.idnum} "
f"{indirect_reference.generation}) does not match actual "
f"({idnum} {generation})."
)
if self.strict:
assert generation == indirect_reference.generation
Expand All @@ -1070,8 +1063,8 @@ def get_object(self, indirect_reference: IndirectObject) -> Optional[PdfObject]:
retval = self._decrypt_object(retval, key) # type: ignore
else:
warnings.warn(
"Object %d %d not defined."
% (indirect_reference.idnum, indirect_reference.generation),
f"Object {indirect_reference.idnum} {indirect_reference.generation} "
"not defined.",
PdfReadWarning,
)
if self.strict:
Expand Down Expand Up @@ -1144,8 +1137,7 @@ def read_object_header(self, stream: StreamType) -> Tuple[int, int]:
stream.seek(-1, 1)
if extra and self.strict:
warnings.warn(
"Superfluous whitespace found in object header %s %s"
% (idnum, generation), # type: ignore
f"Superfluous whitespace found in object header {idnum} {generation}", # type: ignore
PdfReadWarning,
)
return int(idnum), int(generation)
Expand Down Expand Up @@ -1212,9 +1204,8 @@ def read(self, stream: StreamType) -> None:
header_byte = stream.read(5)
if header_byte != b"%PDF-":
raise PdfReadError(
"PDF starts with '{}', but '%PDF-' expected".format(
header_byte.decode("utf8")
)
f"PDF starts with '{header_byte.decode('utf8')}', "
"but '%PDF-' expected"
)
stream.seek(0, os.SEEK_END)
last_mb = stream.tell() - 1024 * 1024 + 1 # offset of last MB of stream
Expand Down Expand Up @@ -1431,7 +1422,7 @@ def _read_pdf15_xref_stream(
entry_sizes = cast(Dict[Any, Any], xrefstream.get("/W"))
assert len(entry_sizes) >= 3
if self.strict and len(entry_sizes) > 3:
raise PdfReadError("Too many entry sizes: %s" % entry_sizes)
raise PdfReadError(f"Too many entry sizes: {entry_sizes}")

def get_entry(i: int) -> Union[int, Tuple[int, ...]]:
# Reads the correct number of bytes for each entry. See the
Expand Down Expand Up @@ -1539,7 +1530,7 @@ def _read_xref_subsections(
if not used_before(num, generation):
self.xref_objStm[num] = (objstr_num, obstr_idx)
elif self.strict:
raise PdfReadError("Unknown xref type: %s" % xref_type)
raise PdfReadError(f"Unknown xref type: {xref_type}")

def _zero_xref(self, generation: int) -> None:
self.xref[generation] = {
Expand Down Expand Up @@ -1568,11 +1559,11 @@ def read_next_end_line(
if stream.tell() < 2:
raise PdfReadError("EOL marker not found")
stream.seek(-2, 1)
if x == b"\n" or x == b"\r": # \n = LF; \r = CR
if x in (b"\n", b"\r"): # \n = LF; \r = CR
crlf = False
while x == b"\n" or x == b"\r":
while x in (b"\n", b"\r"):
x = stream.read(1)
if x == b"\n" or x == b"\r": # account for CR+LF
if x in (b"\n", b"\r"): # account for CR+LF
stream.seek(-1, 1)
crlf = True
if stream.tell() < 2:
Expand Down Expand Up @@ -1657,8 +1648,7 @@ def _decrypt(self, password: Union[str, bytes]) -> int:
encrypt_v = cast(int, encrypt["/V"])
if encrypt_v not in (1, 2):
raise NotImplementedError(
"only algorithm code 1 and 2 are supported. This PDF uses code %s"
% encrypt_v
f"only algorithm code 1 and 2 are supported. This PDF uses code {encrypt_v}"
)
user_password, key = self._authenticate_user_password(password)
if user_password:
Expand Down
24 changes: 11 additions & 13 deletions PyPDF2/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,17 +234,16 @@ def b_(s: Union[str, bytes]) -> bytes:
return bc[s]
if isinstance(s, bytes):
return s
else:
try:
r = s.encode("latin-1")
if len(s) < 2:
bc[s] = r
return r
except Exception:
r = s.encode("utf-8")
if len(s) < 2:
bc[s] = r
return r
try:
r = s.encode("latin-1")
if len(s) < 2:
bc[s] = r
return r
except Exception:
r = s.encode("utf-8")
if len(s) < 2:
bc[s] = r
return r


@overload
Expand Down Expand Up @@ -282,8 +281,7 @@ def ord_(b: int) -> int:
def ord_(b: Union[int, str, bytes]) -> Union[int, bytes]:
if isinstance(b, str):
return ord(b)
else:
return b
return b


def hexencode(b: bytes) -> bytes:
Expand Down
4 changes: 2 additions & 2 deletions PyPDF2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def decode(
str_data = FlateDecode._decode_png_prediction(str_data, columns) # type: ignore
else:
# unsupported predictor
raise PdfReadError("Unsupported flatedecode predictor %r" % predictor)
raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}")
return str_data

@staticmethod
Expand Down Expand Up @@ -492,7 +492,7 @@ def decodeStreamData(stream: Any) -> Union[str, bytes]: # utils.StreamObject
)
else:
# Unsupported filter
raise NotImplementedError("unsupported filter %s" % filter_type)
raise NotImplementedError(f"unsupported filter {filter_type}")
return data


Expand Down
38 changes: 17 additions & 21 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,7 @@ def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfRe
r = read_non_whitespace(stream)
if r != b"R":
raise PdfReadError(
"Error reading indirect object reference at byte %s"
% hex_str(stream.tell())
f"Error reading indirect object reference at byte {hex_str(stream.tell())}"
)
return IndirectObject(int(idnum), int(generation), pdf)

Expand Down Expand Up @@ -298,7 +297,7 @@ def __repr__(self) -> str:
return str(self.quantize(decimal.Decimal(1)))
else:
# Standard formatting adds useless extraneous zeros.
o = "%.5f" % self
o = f"{self:.5f}"
# Remove the zeros.
while o and o[-1] == "0":
o = o[:-1]
Expand Down Expand Up @@ -414,7 +413,6 @@ def readStringFromStream( # TODO: PEP8
b"/": b"/",
b"\\": b"\\",
b" ": b" ",
b"/": b"/",
b"%": b"%",
b"<": b"<",
b">": b">",
Expand Down Expand Up @@ -452,7 +450,7 @@ def readStringFromStream( # TODO: PEP8
# line break was escaped:
tok = b""
else:
msg = r"Unexpected escaped string: {}".format(tok.decode("utf8"))
msg = rf"Unexpected escaped string: {tok.decode('utf8')}"
# if.strict: PdfReadError(msg)
logger.warning(msg)
txt += tok
Expand Down Expand Up @@ -545,7 +543,7 @@ def write_to_stream(
stream.write(b"(")
for c in bytearr:
if not chr(c).isalnum() and c != b" ":
stream.write(b_("\\%03o" % ord_(c)))
stream.write(b_(rf"\{ord_(c):0>3o}"))
else:
stream.write(b_(chr(c)))
stream.write(b")")
Expand Down Expand Up @@ -717,8 +715,8 @@ def read_unsized_from_steam(stream: StreamType, pdf: Any) -> bytes: # PdfReader
tmp = stream.read(2)
if tmp != b"<<":
raise PdfReadError(
"Dictionary read error at byte %s: stream must begin with '<<'"
% hex_str(stream.tell())
f"Dictionary read error at byte {hex_str(stream.tell())}: "
"stream must begin with '<<'"
)
data: Dict[Any, Any] = {}
while True:
Expand All @@ -742,18 +740,16 @@ def read_unsized_from_steam(stream: StreamType, pdf: Any) -> bytes: # PdfReader
value = read_object(stream, pdf, forced_encoding)
if not data.get(key):
data[key] = value
elif pdf.strict:
# multiple definitions of key not permitted
raise PdfReadError(
"Multiple definitions in dictionary at byte %s for key %s"
% (hex_str(stream.tell()), key)
)
else:
warnings.warn(
"Multiple definitions in dictionary at byte %s for key %s"
% (hex_str(stream.tell()), key),
PdfReadWarning,
# multiple definitions of key not permitted
msg = (
f"Multiple definitions in dictionary at byte "
f"{hex_str(stream.tell())} for key {key}"
)
if pdf.strict:
raise PdfReadError(msg)
else:
warnings.warn(msg, PdfReadWarning)

pos = stream.tell()
s = read_non_whitespace(stream)
Expand Down Expand Up @@ -801,8 +797,8 @@ def read_unsized_from_steam(stream: StreamType, pdf: Any) -> bytes: # PdfReader
else:
stream.seek(pos, 0)
raise PdfReadError(
"Unable to find 'endstream' marker after stream at byte %s."
% hex_str(stream.tell())
"Unable to find 'endstream' marker after stream at byte "
f"{hex_str(stream.tell())}."
)
else:
stream.seek(pos, 0)
Expand Down Expand Up @@ -1723,7 +1719,7 @@ def __init__(
elif typ in [TF.FIT, TF.FIT_B]:
pass
else:
raise PdfReadError("Unknown Destination Type: %r" % typ)
raise PdfReadError(f"Unknown Destination Type: {typ!r}")

@property
def dest_array(self) -> ArrayObject:
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/xmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def _identity(value: K) -> K:
def _converter_date(value: str) -> datetime.datetime:
matches = iso8601.match(value)
if matches is None:
raise ValueError("Invalid date format: %s" % value)
raise ValueError(f"Invalid date format: {value}")
year = int(matches.group("year"))
month = int(matches.group("month") or "1")
day = int(matches.group("day") or "1")
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE))
raise RuntimeError(f"Unable to find version string in {VERSIONFILE}.")

setup(version=verstr, package_data={"PyPDF2": ["*.typed"]})