Skip to content

Commit

Permalink
MAINT: Package updates; solve mypy strict remarks (py-pdf#1163)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinThoma authored Jul 24, 2022
1 parent ec30171 commit db3439b
Show file tree
Hide file tree
Showing 15 changed files with 47 additions and 41 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 22.3.0
rev: 22.6.0
hooks:
- id: black
args: [--target-version, py36]
Expand All @@ -40,7 +40,7 @@ repos:
- id: blacken-docs
additional_dependencies: [black==22.1.0]
- repo: https://github.com/asottile/pyupgrade
rev: v2.34.0
rev: v2.37.2
hooks:
- id: pyupgrade
args: [--py36-plus]
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ mutation-results:

benchmark:
pytest tests/bench.py

mypy:
mypy PyPDF2 --ignore-missing-imports --check-untyped --strict
12 changes: 6 additions & 6 deletions PyPDF2/_cmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ def build_char_map(
float(sp_width / 2),
encoding,
# https://github.com/python/mypy/issues/4374
map_dict, # type: ignore
) # type: ignore
map_dict,
)


# used when missing data, e.g. font def missing
unknown_char_map: Tuple[str, float, Union[str, Dict[int, str]], Dict] = (
unknown_char_map: Tuple[str, float, Union[str, Dict[int, str]], Dict[Any, Any]] = (
"Unknown",
9999,
dict(zip(range(256), ["�"] * 256)),
Expand Down Expand Up @@ -108,15 +108,15 @@ def parse_encoding(
encoding: Union[str, List[str], Dict[int, str]] = []
if "/Encoding" not in ft:
try:
if "/BaseFont" in ft and ft["/BaseFont"] in charset_encoding:
if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding:
encoding = dict(
zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])])
)
else:
encoding = "charmap"
return encoding, _default_fonts_space_width[cast(str, ft["/BaseFont"])]
except Exception:
if ft["/Subtype"] == "/Type1":
if cast(str, ft["/Subtype"]) == "/Type1":
return "charmap", space_code
else:
return "", space_code
Expand Down Expand Up @@ -314,7 +314,7 @@ def compute_space_width(
except Exception:
w1[-1] = 1000.0
if "/W" in ft1:
w = list(ft1["/W"]) # type: ignore
w = list(ft1["/W"])
else:
w = []
while len(w) > 0:
Expand Down
6 changes: 3 additions & 3 deletions PyPDF2/_encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
import random
import struct
from enum import IntEnum
from typing import Optional, Tuple, Union, cast
from typing import Any, Dict, Optional, Tuple, Union, cast

from PyPDF2.errors import DependencyError
from PyPDF2._utils import logger_warning
from PyPDF2.errors import DependencyError
from PyPDF2.generic import (
ArrayObject,
ByteStringObject,
Expand Down Expand Up @@ -566,7 +566,7 @@ def verify_perms(
@staticmethod
def generate_values(
user_pwd: bytes, owner_pwd: bytes, key: bytes, p: int, metadata_encrypted: bool
) -> dict:
) -> Dict[Any, Any]:
u_value, ue_value = AlgV5.compute_U_value(user_pwd, key)
o_value, oe_value = AlgV5.compute_O_value(owner_pwd, key, u_value)
perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted)
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/_merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ def find_bookmark(
res = self.find_bookmark(bookmark, b) # type: ignore
if res:
return [i] + res
elif b == bookmark or b["/Title"] == bookmark:
elif b == bookmark or cast(Dict[Any, Any], b["/Title"]) == bookmark:
# we found a leaf node
return [i]

Expand Down
8 changes: 4 additions & 4 deletions PyPDF2/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,9 +506,9 @@ def _merge_page(
# Combine /ProcSet sets.
new_resources[NameObject(RES.PROC_SET)] = ArrayObject(
frozenset(
original_resources.get(RES.PROC_SET, ArrayObject()).get_object() # type: ignore
original_resources.get(RES.PROC_SET, ArrayObject()).get_object()
).union(
frozenset(page2resources.get(RES.PROC_SET, ArrayObject()).get_object()) # type: ignore
frozenset(page2resources.get(RES.PROC_SET, ArrayObject()).get_object())
)
)

Expand Down Expand Up @@ -1248,7 +1248,7 @@ def process_operation(operator: bytes, operands: List) -> None:
cmaps[operands[0]][2],
cmaps[operands[0]][3],
operands[0],
) # type:ignore
)
except KeyError: # font not found
_space_width = unknown_char_map[1]
cmap = (
Expand Down Expand Up @@ -1395,7 +1395,7 @@ def process_operation(operator: bytes, operands: List) -> None:
except IndexError:
pass
try:
xobj = resources_dict["/XObject"] # type: ignore
xobj = resources_dict["/XObject"]
if xobj[operands[0]]["/Subtype"] != "/Image": # type: ignore
# output += text
text = self.extract_xform_text(xobj[operands[0]], space_width) # type: ignore
Expand Down
8 changes: 5 additions & 3 deletions PyPDF2/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,9 @@ def _build_outline(self, node: DictionaryObject) -> Optional[Destination]:
elif isinstance(dest, str):
# named destination, addresses NameObject Issue #193
try:
outline = self._build_destination(title, self._namedDests[dest].dest_array) # type: ignore
outline = self._build_destination(
title, self._namedDests[dest].dest_array
)
except KeyError:
# named destination not found in Name Dict
outline = self._build_destination(title, None)
Expand Down Expand Up @@ -1045,7 +1047,7 @@ def _get_object_from_stream(
stmnum, idx = self.xref_objStm[indirect_reference.idnum]
obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore
# This is an xref to a stream, so its type better be a stream
assert obj_stm["/Type"] == "/ObjStm"
assert cast(str, obj_stm["/Type"]) == "/ObjStm"
# /N is the number of indirect objects in the stream
assert idx < obj_stm["/N"]
stream_data = BytesIO(b_(obj_stm.get_data())) # type: ignore
Expand Down Expand Up @@ -1501,7 +1503,7 @@ def _read_pdf15_xref_stream(
stream.seek(-1, 1)
idnum, generation = self.read_object_header(stream)
xrefstream = cast(ContentStream, read_object(stream, self))
assert xrefstream["/Type"] == "/XRef"
assert cast(str, xrefstream["/Type"]) == "/XRef"
self.cache_indirect_object(generation, idnum, xrefstream)
stream_data = BytesIO(b_(xrefstream.get_data()))
# Index pairs specify the subsections in the dictionary. If
Expand Down
4 changes: 2 additions & 2 deletions PyPDF2/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
# Python 3.10+: https://www.python.org/dev/peps/pep-0484/
from typing import TypeAlias # type: ignore[attr-defined]
except ImportError:
from typing_extensions import TypeAlias # type: ignore[misc]
from typing_extensions import TypeAlias

from .errors import STREAM_TRUNCATED_PREMATURELY, PdfStreamError

Expand Down Expand Up @@ -130,7 +130,7 @@ def skip_over_comment(stream: StreamType) -> None:


def read_until_regex(
stream: StreamType, regex: Pattern, ignore_eof: bool = False
stream: StreamType, regex: Pattern[bytes], ignore_eof: bool = False
) -> bytes:
"""
Read until the regular expression pattern matched (ignore the match).
Expand Down
4 changes: 2 additions & 2 deletions PyPDF2/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def getObject(self, ido: IndirectObject) -> PdfObject: # pragma: no cover
def _add_page(
self, page: PageObject, action: Callable[[Any, IndirectObject], None]
) -> None:
assert page[PA.TYPE] == CO.PAGE
assert cast(str, page[PA.TYPE]) == CO.PAGE
if page.pdf is not None:
other = page.pdf.pdf_header
if isinstance(other, str):
Expand Down Expand Up @@ -292,7 +292,7 @@ def get_page(
raise ValueError("Please specify the page_number")
pages = cast(Dict[str, Any], self.get_object(self._pages))
# TODO: crude hack
return pages[PA.KIDS][page_number].get_object()
return cast(PageObject, pages[PA.KIDS][page_number].get_object())

def getPage(self, pageNumber: int) -> PageObject: # pragma: no cover
"""
Expand Down
4 changes: 2 additions & 2 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def readFromStream(stream: StreamType) -> "BooleanObject": # pragma: no cover


class ArrayObject(list, PdfObject):
def items(self) -> Iterable:
def items(self) -> Iterable[Any]:
"""
Emulate DictionaryObject.items for a list
(index, object)
Expand Down Expand Up @@ -517,7 +517,7 @@ def read_string_from_stream(
return create_string_object(txt, forced_encoding)


class ByteStringObject(bytes, PdfObject): # type: ignore
class ByteStringObject(bytes, PdfObject):
"""
Represents a string object where the text encoding could not be determined.
This occurs quite often, as the PDF spec doesn't provide an alternate way to
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# Python 3.10+: https://www.python.org/dev/peps/pep-0484/
from typing import TypeAlias # type: ignore[attr-defined]
except ImportError:
from typing_extensions import TypeAlias # type: ignore[misc]
from typing_extensions import TypeAlias

from .generic import (
ArrayObject,
Expand Down
3 changes: 2 additions & 1 deletion PyPDF2/xmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
Optional,
TypeVar,
Union,
cast,
)
from xml.dom.minidom import Document
from xml.dom.minidom import Element as XmlElement
Expand Down Expand Up @@ -482,7 +483,7 @@ def xmpmm_documentId(self, value: str) -> None: # pragma: no cover
@property
def xmpmm_instanceId(self) -> str: # pragma: no cover
deprecate_with_replacement("xmpmm_instanceId", "xmpmm_instance_id")
return self.xmpmm_instance_id
return cast(str, self.xmpmm_instance_id)

@xmpmm_instanceId.setter
def xmpmm_instanceId(self, value: str) -> None: # pragma: no cover
Expand Down
8 changes: 4 additions & 4 deletions requirements/ci.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ flake8==4.0.1
# via
# -r requirements/ci.in
# flake8-bugbear
flake8-bugbear==22.4.25
flake8-bugbear==22.7.1
# via -r requirements/ci.in
flake8-implicit-str-concat==0.2.0
# via -r requirements/ci.in
Expand All @@ -30,7 +30,7 @@ mccabe==0.6.1
# via flake8
more-itertools==8.13.0
# via flake8-implicit-str-concat
mypy==0.961
mypy==0.971
# via -r requirements/ci.in
mypy-extensions==0.4.3
# via mypy
Expand All @@ -46,7 +46,7 @@ py-cpuinfo==8.0.0
# via pytest-benchmark
pycodestyle==2.8.0
# via flake8
pycryptodome==3.14.1
pycryptodome==3.15.0
# via -r requirements/ci.in
pyflakes==2.4.0
# via flake8
Expand All @@ -66,7 +66,7 @@ typed-ast==1.5.4
# via mypy
typeguard==2.13.3
# via -r requirements/ci.in
types-pillow==9.0.20
types-pillow==9.2.0
# via -r requirements/ci.in
typing-extensions==4.1.1
# via
Expand Down
12 changes: 6 additions & 6 deletions requirements/dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
#
attrs==21.4.0
# via pytest
black==22.3.0
black==22.6.0
# via -r requirements/dev.in
bleach==4.1.0
# via readme-renderer
certifi==2022.6.15
# via requests
cffi==1.15.0
cffi==1.15.1
# via cryptography
cfgv==3.3.1
# via pre-commit
Expand All @@ -26,11 +26,11 @@ colorama==0.4.5
# via twine
coverage[toml]==6.2
# via pytest-cov
cryptography==37.0.2
cryptography==37.0.4
# via secretstorage
dataclasses==0.8
# via black
distlib==0.3.4
distlib==0.3.5
# via virtualenv
docutils==0.18.1
# via readme-renderer
Expand Down Expand Up @@ -135,11 +135,11 @@ typing-extensions==4.1.1
# via
# black
# importlib-metadata
urllib3==1.26.9
urllib3==1.26.10
# via
# requests
# twine
virtualenv==20.14.1
virtualenv==20.15.1
# via pre-commit
webencodings==0.5.1
# via bleach
Expand Down
8 changes: 4 additions & 4 deletions requirements/docs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ alabaster==0.7.12
# via sphinx
attrs==21.4.0
# via markdown-it-py
babel==2.10.1
babel==2.10.3
# via sphinx
certifi==2022.5.18.1
certifi==2022.6.15
# via requests
charset-normalizer==2.0.12
# via requests
Expand All @@ -21,7 +21,7 @@ docutils==0.17.1
# sphinx-rtd-theme
idna==3.3
# via requests
imagesize==1.3.0
imagesize==1.4.1
# via sphinx
importlib-metadata==4.8.3
# via sphinx
Expand Down Expand Up @@ -78,7 +78,7 @@ typing-extensions==4.1.1
# via
# importlib-metadata
# markdown-it-py
urllib3==1.26.9
urllib3==1.26.10
# via requests
zipp==3.6.0
# via importlib-metadata

0 comments on commit db3439b

Please sign in to comment.