Skip to content

Commit

Permalink
MAINT: Remove unnecessary property + mypy fixes (#2099)
Browse files Browse the repository at this point in the history
While on it, pre-commit was also updated + several fixes for mypy.

Taken from #2086

Full credit to Lucas for the property-simplification.

Co-authored-by: Lucas Cimon <[email protected]>
  • Loading branch information
MartinThoma and Lucas-C authored Aug 19, 2023
1 parent 0d3dded commit b39ac96
Show file tree
Hide file tree
Showing 13 changed files with 46 additions and 49 deletions.
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,29 @@ repos:
- id: black
args: [--target-version, py36]
- repo: https://github.com/asottile/blacken-docs
rev: 1.15.0
rev: 1.16.0
hooks:
- id: blacken-docs
additional_dependencies: [black==22.1.0]
exclude: "docs/user/robustness.md"
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.280'
rev: 'v0.0.285'
hooks:
- id: ruff
args: ['--fix']
- repo: https://github.com/asottile/pyupgrade
rev: v3.9.0
rev: v3.10.1
hooks:
- id: pyupgrade
args: [--py36-plus]
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
rev: 6.1.0
hooks:
- id: flake8
args: ["--ignore", "E,W,F"]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v1.4.1'
rev: 'v1.5.1'
hooks:
- id: mypy
files: ^pypdf/.*
Expand Down
4 changes: 2 additions & 2 deletions docs/user/encryption-decryption.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Encryption and Decryption of PDFs

PDF encryption makes use of [`RC4`](https://en.wikipedia.org/wiki/RC4) and
[`AES`](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) algorithms
PDF encryption makes use of [`RC4`](https://en.wikipedia.org/wiki/RC4) and
[`AES`](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) algorithms
with different key length. `pypdf` supports all of them until `PDF-2.0`, which
is the latest PDF standard.

Expand Down
2 changes: 1 addition & 1 deletion pypdf/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ def rotation(self) -> int:
return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object()

@rotation.setter
def rotation(self, r: Union[int, float]) -> None:
def rotation(self, r: float) -> None:
self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360)

def transfer_rotation_to_content(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion pypdf/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ def decode(
return tiff_header + data


def decode_stream_data(stream: Any) -> Union[str, bytes]: # utils.StreamObject
def decode_stream_data(stream: Any) -> bytes: # utils.StreamObject
"""
Decode the stream data based on the specified filters.
Expand Down
4 changes: 2 additions & 2 deletions pypdf/generic/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def get_object(self) -> Optional["PdfObject"]:
def __repr__(self) -> str:
return f"IndirectObject({self.idnum!r}, {self.generation!r}, {id(self.pdf)})"

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
return (
other is not None
and isinstance(other, IndirectObject)
Expand All @@ -321,7 +321,7 @@ def __eq__(self, other: Any) -> bool:
and self.pdf is other.pdf
)

def __ne__(self, other: Any) -> bool:
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)

def write_to_stream(
Expand Down
14 changes: 3 additions & 11 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ def _reset_node_tree_relationship(child_obj: Any) -> None:

class StreamObject(DictionaryObject):
def __init__(self) -> None:
self.__data: Optional[str] = None
self._data: bytes = b""
self.decoded_self: Optional[DecodedStreamObject] = None

def _clone(
Expand Down Expand Up @@ -833,14 +833,6 @@ def decodedSelf(self, value: "DecodedStreamObject") -> None: # deprecated
deprecation_with_replacement("decodedSelf", "decoded_self", "3.0.0")
self.decoded_self = value

@property
def _data(self) -> Any:
return self.__data

@_data.setter
def _data(self, value: Any) -> None:
self.__data = value

def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
) -> None:
Expand Down Expand Up @@ -1181,8 +1173,8 @@ def _read_inline_image(self, stream: StreamType) -> Dict[str, Any]:
data.write(info)
return {"settings": settings, "data": data.getvalue()}

@property
def _data(self) -> bytes:
@property # type: ignore
def _data(self) -> bytes: # type: ignore
new_data = BytesIO()
for operands, operator in self.operations:
if operator == b"INLINE IMAGE":
Expand Down
4 changes: 2 additions & 2 deletions pypdf/pagerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .errors import ParseError

_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0".
PAGE_RANGE_RE = "^({int}|({int}?(:{int}?(:{int}?)?)))$".format(int=_INT_RE)
PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$"
# groups: 12 34 5 6 7 8


Expand Down Expand Up @@ -127,7 +127,7 @@ def indices(self, n: int) -> Tuple[int, int, int]:
"""
return self._slice.indices(n)

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, PageRange):
return False
return self._slice == other._slice
Expand Down
7 changes: 5 additions & 2 deletions pypdf/papersizes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""Helper to get paper sizes."""

from collections import namedtuple
from typing import NamedTuple

Dimensions = namedtuple("Dimensions", ["width", "height"])

class Dimensions(NamedTuple):
width: int
height: int


class PaperSize:
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ ignore = [
"PD011", # Use `.to_numpy()` instead of `.values`
"FA102", # Missing `from __future__ import annotations`, but uses PEP 604 union
"PERF203", # `try`-`except` within a loop incurs performance overhead
"PYI042", # Type alias `mode_str_type` should be CamelCase
# Ruff bug
"PT014", # Duplicate of test case at index 1 in `@pytest_mark.parametrize`
]

[tool.ruff.per-file-ignores]
Expand Down
14 changes: 7 additions & 7 deletions requirements/ci-3.11.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
#
attrs==23.1.0
# via flake8-bugbear
coverage==7.2.7
coverage==7.3.0
# via -r requirements/ci.in
flake8==6.0.0
flake8==6.1.0
# via
# -r requirements/ci.in
# flake8-bugbear
Expand All @@ -25,7 +25,7 @@ iniconfig==2.0.0
# via pytest
mccabe==0.7.0
# via flake8
mypy==1.4.1
mypy==1.5.1
# via -r requirements/ci.in
mypy-extensions==1.0.0
# via mypy
Expand All @@ -39,13 +39,13 @@ pluggy==1.2.0
# via pytest
py-cpuinfo==9.0.0
# via pytest-benchmark
pycodestyle==2.10.0
pycodestyle==2.11.0
# via
# flake8
# flake8-print
pycryptodome==3.18.0
# via -r requirements/ci.in
pyflakes==3.0.1
pyflakes==3.1.0
# via flake8
pytest==7.4.0
# via
Expand All @@ -59,9 +59,9 @@ pytest-socket==0.6.0
# via -r requirements/ci.in
pytest-timeout==2.1.0
# via -r requirements/ci.in
ruff==0.0.280
ruff==0.0.285
# via -r requirements/ci.in
typeguard==4.0.1
typeguard==4.1.2
# via -r requirements/ci.in
types-dataclasses==0.6.6
# via -r requirements/ci.in
Expand Down
2 changes: 1 addition & 1 deletion tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ class Tst: # to replace pdf
# TODO: What should happen with the stream?
assert do == {"/S": "/GoTo"}
if length in (6, 10):
assert b"BT /F1" in do._StreamObject__data
assert b"BT /F1" in do._data
raise PdfReadError("__ALLGOOD__")
assert should_fail ^ (exc.value.args[0] == "__ALLGOOD__")

Expand Down
2 changes: 1 addition & 1 deletion tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -1458,4 +1458,4 @@ def test_issue_140():
name = "issue-140.pdf"
b = get_data_from_url(url, name=name)
reader = PdfReader(BytesIO(b))
assert (len(reader.pages) == 54)
assert len(reader.pages) == 54
27 changes: 13 additions & 14 deletions tests/test_text_extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,19 @@ def test_multi_language(visitor_text):
assert "حَبيبي" in reader.pages[3].extract_text(visitor_text=visitor_text)


@pytest.mark.parametrize(("file_name", "constraints"),
[
("inkscape-abc.pdf",
{"A": lambda x, y:
0 < x < 94 and
189 < y < 283, # In upper left
"B": lambda x, y:
94 < x < 189 and
94 < y < 189, # In the center
"C": lambda x, y:
189 < x < 283 and
0 < y < 94} # In lower right
)
])
@pytest.mark.parametrize(
("file_name", "constraints"),
[
(
"inkscape-abc.pdf",
{
"A": lambda x, y: 0 < x < 94 and 189 < y < 283, # In upper left
"B": lambda x, y: 94 < x < 189 and 94 < y < 189, # In the center
"C": lambda x, y: 189 < x < 283 and 0 < y < 94,
}, # In lower right
)
],
)
def test_visitor_text_matrices(file_name, constraints):
"""
Checks if the matrices given to the visitor_text function when calling
Expand Down

0 comments on commit b39ac96

Please sign in to comment.