Skip to content

Commit

Permalink
MAINT: Use Python 3.6 language features (#849)
Browse files Browse the repository at this point in the history
As support for Python 3.5 and lower was dropped, we can use more modern syntax
  • Loading branch information
MartinThoma authored May 1, 2022
1 parent 5c9df42 commit cd495f7
Show file tree
Hide file tree
Showing 20 changed files with 49 additions and 57 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Replace this: What happened? What were you trying to achieve?

Which environment were you using when you encountered the problem?

```python
```bash
$ python -m platform
# TODO: Your output goes here

Expand Down
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ repos:
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
exclude: "resources/.*"
- id: trailing-whitespace
- id: mixed-line-ending
- id: check-added-large-files
Expand Down Expand Up @@ -45,3 +46,8 @@ repos:
hooks:
- id: blacken-docs
additional_dependencies: [black==22.1.0]
- repo: https://github.com/asottile/pyupgrade
rev: v2.31.0
hooks:
- id: pyupgrade
args: [--py36-plus]
2 changes: 0 additions & 2 deletions PyPDF2/_page.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <[email protected]>
#
Expand Down
8 changes: 3 additions & 5 deletions PyPDF2/_reader.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <[email protected]>
#
Expand Down Expand Up @@ -168,7 +166,7 @@ def producer_raw(self):
return self.get(DI.PRODUCER)


class PdfFileReader(object):
class PdfFileReader:
"""
Initialize a PdfFileReader object.
Expand Down Expand Up @@ -862,7 +860,7 @@ def cacheGetIndirectObject(self, generation, idnum):

def cacheIndirectObject(self, generation, idnum, obj):
if (generation, idnum) in self.resolvedObjects:
msg = "Overwriting cache for %s %s" % (generation, idnum)
msg = f"Overwriting cache for {generation} {idnum}"
if self.strict:
raise PdfReadError(msg)
else:
Expand Down Expand Up @@ -900,7 +898,7 @@ def read(self, stream):
raise PdfReadError("Broken xref table")
else:
warnings.warn(
"incorrect startxref pointer({})".format(xref_issue_nr), PdfReadWarning
f"incorrect startxref pointer({xref_issue_nr})", PdfReadWarning
)

# read all cross reference tables and their trailers
Expand Down
2 changes: 0 additions & 2 deletions PyPDF2/_security.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <[email protected]>
#
Expand Down
8 changes: 3 additions & 5 deletions PyPDF2/_writer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <[email protected]>
#
Expand Down Expand Up @@ -69,7 +67,7 @@
logger = logging.getLogger(__name__)


class PdfFileWriter(object):
class PdfFileWriter:
"""
This class supports writing PDF files out, given pages produced by another
class (typically :class:`PdfFileReader<PdfFileReader>`).
Expand Down Expand Up @@ -634,7 +632,7 @@ def _sweepIndirectReferences(self, externMap, data):
else:
if hasattr(data.pdf, "stream") and data.pdf.stream.closed:
raise ValueError(
"I/O operation on closed file: {}".format(data.pdf.stream.name)
f"I/O operation on closed file: {data.pdf.stream.name}"
)
newobj = (
externMap.get(data.pdf, {})
Expand Down Expand Up @@ -771,7 +769,7 @@ def addBookmark(
bold=False,
italic=False,
fit="/Fit",
*args
*args,
):
"""
Add a bookmark to this PDF file.
Expand Down
19 changes: 9 additions & 10 deletions PyPDF2/filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2006, Mathieu Fenniak
# All rights reserved.
#
Expand Down Expand Up @@ -121,7 +120,7 @@ def compress(data):
return retval


class FlateDecode(object):
class FlateDecode:
@staticmethod
def decode(data, decodeParms):
"""
Expand Down Expand Up @@ -203,7 +202,7 @@ def encode(data):
return compress(data)


class ASCIIHexDecode(object):
class ASCIIHexDecode:
"""
The ASCIIHexDecode filter decodes data that has been encoded in ASCII
hexadecimal form into a base-7 ASCII format.
Expand Down Expand Up @@ -239,12 +238,12 @@ def decode(data, decodeParms=None):
return retval


class LZWDecode(object):
class LZWDecode:
"""Taken from:
http://www.java2s.com/Open-Source/Java-Document/PDF/PDF-Renderer/com/sun/pdfview/decode/LZWDecode.java.htm
"""

class decoder(object):
class decoder:
def __init__(self, data):
self.STOP = 257
self.CLEARDICT = 256
Expand Down Expand Up @@ -334,7 +333,7 @@ def decode(data, decodeParms=None):
return LZWDecode.decoder(data).decode()


class ASCII85Decode(object):
class ASCII85Decode:
"""Decodes string ASCII85-encoded data into a byte format."""

@staticmethod
Expand Down Expand Up @@ -362,19 +361,19 @@ def decode(data, decodeParms=None):
return bytes(out)


class DCTDecode(object):
class DCTDecode:
@staticmethod
def decode(data, decodeParms=None):
return data


class JPXDecode(object):
class JPXDecode:
@staticmethod
def decode(data, decodeParms=None):
return data


class CCITParameters(object):
class CCITParameters:
"""TABLE 3.9 Optional parameters for the CCITTFaxDecode filter"""

def __init__(self, K=0, columns=0, rows=0):
Expand All @@ -397,7 +396,7 @@ def group(self):
return CCITTgroup


class CCITTFaxDecode(object):
class CCITTFaxDecode:
"""
See 3.3.5 CCITTFaxDecode Filter (PDF 1.7 Standard).
Expand Down
17 changes: 8 additions & 9 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2006, Mathieu Fenniak
# All rights reserved.
#
Expand Down Expand Up @@ -102,7 +101,7 @@ def readObject(stream, pdf):
return NumberObject.readFromStream(stream)


class PdfObject(object):
class PdfObject:
def getObject(self):
"""Resolve indirect references."""
return self
Expand Down Expand Up @@ -182,7 +181,7 @@ def getObject(self):
return self.pdf.getObject(self).getObject()

def __repr__(self):
return "IndirectObject(%r, %r)" % (self.idnum, self.generation)
return f"IndirectObject({self.idnum!r}, {self.generation!r})"

def __eq__(self, other):
return (
Expand All @@ -197,7 +196,7 @@ def __ne__(self, other):
return not self.__eq__(other)

def writeToStream(self, stream, encryption_key):
stream.write(b_("%s %s R" % (self.idnum, self.generation)))
stream.write(b_(f"{self.idnum} {self.generation} R"))

@staticmethod
def readFromStream(stream, pdf):
Expand Down Expand Up @@ -238,7 +237,7 @@ def __new__(cls, value="0", context=None):
except decimal.InvalidOperation:
# If this isn't a valid decimal (happens in malformed PDFs)
# fallback to 0
logger.warning("Invalid FloatObject {}".format(value))
logger.warning(f"Invalid FloatObject {value}")
return decimal.Decimal.__new__(cls, "0")

def __repr__(self):
Expand Down Expand Up @@ -1077,16 +1076,16 @@ def getUpperRight(self):
return self.getUpperRight_x(), self.getUpperRight_y()

def setLowerLeft(self, value):
self[0], self[1] = [self.ensureIsNumber(x) for x in value]
self[0], self[1] = (self.ensureIsNumber(x) for x in value)

def setLowerRight(self, value):
self[2], self[1] = [self.ensureIsNumber(x) for x in value]
self[2], self[1] = (self.ensureIsNumber(x) for x in value)

def setUpperLeft(self, value):
self[0], self[3] = [self.ensureIsNumber(x) for x in value]
self[0], self[3] = (self.ensureIsNumber(x) for x in value)

def setUpperRight(self, value):
self[2], self[3] = [self.ensureIsNumber(x) for x in value]
self[2], self[3] = (self.ensureIsNumber(x) for x in value)

def getWidth(self):
return self.getUpperRight_x() - self.getLowerLeft_x()
Expand Down
10 changes: 6 additions & 4 deletions PyPDF2/merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
StreamIO = BytesIO


class _MergedPage(object):
class _MergedPage:
"""
_MergedPage is used internally by PdfFileMerger to collect necessary
information on each page that is being merged.
Expand All @@ -51,7 +51,7 @@ def __init__(self, pagedata, src, id):
self.id = id


class PdfFileMerger(object):
class PdfFileMerger:
"""
Initializes a ``PdfFileMerger`` object. ``PdfFileMerger`` merges multiple
PDFs into a single PDF. It can concatenate, slice, insert, or any
Expand Down Expand Up @@ -466,7 +466,9 @@ def _associate_dests_to_pages(self, pages):
if pageno is not None:
nd[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError("Unresolved named destination '%s'" % (nd["/Title"],))
raise ValueError(
"Unresolved named destination '{}'".format(nd["/Title"])
)

def _associate_bookmarks_to_pages(self, pages, bookmarks=None):
if bookmarks is None:
Expand All @@ -490,7 +492,7 @@ def _associate_bookmarks_to_pages(self, pages, bookmarks=None):
if pageno is not None:
b[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError("Unresolved bookmark '%s'" % (b["/Title"],))
raise ValueError("Unresolved bookmark '{}'".format(b["/Title"]))

def findBookmark(self, bookmark, root=None):
if root is None:
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/pagerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"""


class PageRange(object):
class PageRange:
"""
A slice-like representation of a range of page indices,
i.e. page numbers, only starting at zero.
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/papersizes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Dimensions = namedtuple("Dimensions", ["width", "height"])


class PaperSize(object):
class PaperSize:
"""(width, height) of the paper in portrait mode in pixels at 72 ppi."""

# Notes how to calculate it:
Expand Down
4 changes: 2 additions & 2 deletions PyPDF2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def readUntilRegex(stream, regex, ignore_eof=False):
return name


class ConvertFunctionsToVirtualList(object):
class ConvertFunctionsToVirtualList:
def __init__(self, lengthFunction, getFunction):
self.lengthFunction = lengthFunction
self.getFunction = getFunction
Expand Down Expand Up @@ -153,7 +153,7 @@ def RC4_encrypt(key, plaintext):

def matrixMultiply(a, b):
return [
[sum([float(i) * float(j) for i, j in zip(row, col)]) for col in zip(*b)]
[sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)]
for row in a
]

Expand Down
5 changes: 2 additions & 3 deletions PyPDF2/xmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ def getElement(self, aboutUri, namespace, name):
attr = desc.getAttributeNodeNS(namespace, name)
if attr is not None:
yield attr
for element in desc.getElementsByTagNameNS(namespace, name):
yield element
yield from desc.getElementsByTagNameNS(namespace, name)

def getNodesInNamespace(self, aboutUri, namespace):
for desc in self.rdfRoot.getElementsByTagNameNS(RDF_NAMESPACE, "Description"):
Expand Down Expand Up @@ -116,7 +115,7 @@ def _converter_date(value):
tzd = matches.group("tzd") or "Z"
dt = datetime.datetime(year, month, day, hour, minute, seconds, milliseconds)
if tzd != "Z":
tzd_hours, tzd_minutes = [int(x) for x in tzd.split(":")]
tzd_hours, tzd_minutes = (int(x) for x in tzd.split(":"))
tzd_hours *= -1
if tzd_hours < 0:
tzd_minutes *= -1
Expand Down
2 changes: 1 addition & 1 deletion make_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def version_bump(git_tag: str) -> str:


def get_changelog(changelog_path: str) -> str:
with open(changelog_path, "r") as fh:
with open(changelog_path) as fh:
changelog = fh.read()
return changelog

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from setuptools import setup

VERSIONFILE = "PyPDF2/_version.py"
with open(VERSIONFILE, "rt") as fp:
with open(VERSIONFILE) as fp:
verstrline = fp.read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
Expand Down
1 change: 0 additions & 1 deletion tests/test_filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import string
from itertools import product as cartesian_product

Expand Down
1 change: 0 additions & 1 deletion tests/test_generic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from io import BytesIO

import pytest
Expand Down
7 changes: 3 additions & 4 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import io
import os

Expand Down Expand Up @@ -94,6 +93,6 @@ def test_hexStr():

def test_b():
assert PyPDF2.utils.b_("foo") == b"foo"
assert PyPDF2.utils.b_("😀") == "😀".encode("utf-8")
assert PyPDF2.utils.b_("‰") == "‰".encode("utf-8")
assert PyPDF2.utils.b_("▷") == "▷".encode("utf-8")
assert PyPDF2.utils.b_("😀") == "😀".encode()
assert PyPDF2.utils.b_("‰") == "‰".encode()
assert PyPDF2.utils.b_("▷") == "▷".encode()
4 changes: 1 addition & 3 deletions tests/test_workflows.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import binascii
import os
import sys
Expand Down Expand Up @@ -54,7 +52,7 @@ def test_PdfReaderJpegImage():
reader = PdfFileReader(inputfile)

# Retrieve the text of the image
with open(os.path.join(RESOURCE_ROOT, "jpeg.txt"), "r") as pdftext_file:
with open(os.path.join(RESOURCE_ROOT, "jpeg.txt")) as pdftext_file:
imagetext = pdftext_file.read()

page = reader.getPage(0)
Expand Down
Loading

0 comments on commit cd495f7

Please sign in to comment.