Skip to content

Commit

Permalink
DEP: Rename names to be PEP8-compliant (#967)
Browse files Browse the repository at this point in the history
All of the following get in [the deprecation process](https://pypdf2.readthedocs.io/en/latest/dev/deprecations.html). This means the old parameters will work for a while to give users a chance to migrate without service disruptions.

`PdfWriter.get_page`: the pageNumber parameter is renamed to page_number

`PyPDF2.filters`:

* For all classes, a parameter rename: decodeParms ➔ decode_parms
* decodeStreamData ➔ decode_stream_data

`PyPDF2.xmp`:

* XmpInformation.rdfRoot ➔ XmpInformation.rdf_root
* XmpInformation.xmp_createDate ➔ XmpInformation.xmp_create_date
* XmpInformation.xmp_creatorTool ➔ XmpInformation.xmp_creator_tool
* XmpInformation.xmp_metadataDate ➔ XmpInformation.xmp_metadata_date
* XmpInformation.xmp_modifyDate ➔ XmpInformation.xmp_modify_date
* XmpInformation.xmpMetadata ➔ XmpInformation.xmp_metadata
* XmpInformation.xmpmm_documentId ➔ XmpInformation.xmpmm_document_id
* XmpInformation.xmpmm_instanceId ➔ XmpInformation.xmpmm_instance_id

`PyPDF2.generic`:

* readHexStringFromStream ➔ read_hex_string_from_stream
* initializeFromDictionary ➔ initialize_from_dictionary
* createStringObject ➔ create_string_object
* TreeObject.hasChildren ➔ TreeObject.has_children
* TreeObject.emptyTree ➔ TreeObject.empty_tree
  • Loading branch information
MartinThoma authored Jun 19, 2022
1 parent 797963a commit 953a11d
Show file tree
Hide file tree
Showing 9 changed files with 240 additions and 92 deletions.
4 changes: 2 additions & 2 deletions PyPDF2/_encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
PdfObject,
StreamObject,
TextStringObject,
createStringObject,
create_string_object,
)


Expand Down Expand Up @@ -172,7 +172,7 @@ def encrypt_object(self, obj: PdfObject) -> PdfObject:
def decrypt_object(self, obj: PdfObject) -> PdfObject:
if isinstance(obj, ByteStringObject) or isinstance(obj, TextStringObject):
data = self.strCrypt.decrypt(obj.original_bytes)
obj = createStringObject(data)
obj = create_string_object(data)
elif isinstance(obj, StreamObject):
obj._data = self.stmCrypt.decrypt(obj._data)
elif isinstance(obj, DictionaryObject):
Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def _alg35(
return val + (b"\x00" * 16), key


def RC4_encrypt(key: Union[str, bytes], plaintext: bytes) -> bytes:
def RC4_encrypt(key: Union[str, bytes], plaintext: bytes) -> bytes: # TODO
S = list(range(256))
j = 0
for i in range(256):
Expand Down
32 changes: 22 additions & 10 deletions PyPDF2/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
TextStringObject,
TreeObject,
_create_bookmark,
createStringObject,
create_string_object,
)
from .types import (
BookmarkTypes,
Expand Down Expand Up @@ -108,7 +108,7 @@ def __init__(self) -> None:
info = DictionaryObject()
info.update(
{
NameObject("/Producer"): createStringObject(
NameObject("/Producer"): create_string_object(
codecs.BOM_UTF16_BE + "PyPDF2".encode("utf-16be")
)
}
Expand Down Expand Up @@ -215,18 +215,30 @@ def insertPage(self, page: PageObject, index: int = 0) -> None: # pragma: no co
deprecate_with_replacement("insertPage", "insert_page")
self.insert_page(page, index)

def get_page(self, pageNumber: int) -> PageObject: # TODO: PEP8
def get_page(
self, page_number: Optional[int] = None, pageNumber: Optional[int] = None
) -> PageObject:
"""
Retrieve a page by number from this PDF file.
:param int pageNumber: The page number to retrieve
:param int page_number: The page number to retrieve
(pages begin at zero)
:return: the page at the index given by *pageNumber*
:return: the page at the index given by *page_number*
:rtype: :class:`PageObject<PyPDF2._page.PageObject>`
"""
if pageNumber is not None: # pragma: no cover
if page_number is not None:
raise ValueError("Please only use the page_number parameter")
else:
deprecate_with_replacement(
"get_page(pageNumber)", "get_page(page_number)", "4.0.0"
)
page_number = pageNumber
if page_number is None and pageNumber is None: # pragma: no cover
raise ValueError("Please specify the page_number")
pages = cast(Dict[str, Any], self.get_object(self._pages))
# TODO: crude hack
return pages[PA.KIDS][pageNumber].get_object()
return pages[PA.KIDS][page_number].get_object()

def getPage(self, pageNumber: int) -> PageObject: # pragma: no cover
"""
Expand Down Expand Up @@ -362,7 +374,7 @@ def add_js(self, javascript: str) -> None:
NameObject("/JavaScript"): DictionaryObject(
{
NameObject(CA.NAMES): ArrayObject(
[createStringObject(js_string_name), js_indirect_object]
[create_string_object(js_string_name), js_indirect_object]
)
}
)
Expand Down Expand Up @@ -434,7 +446,7 @@ def add_attachment(self, filename: str, data: Union[str, bytes]) -> None:
filespec.update(
{
NameObject(PA.TYPE): NameObject("/Filespec"),
NameObject("/F"): createStringObject(
NameObject("/F"): create_string_object(
filename
), # Perhaps also try TextStringObject
NameObject("/EF"): ef_entry,
Expand All @@ -456,7 +468,7 @@ def add_attachment(self, filename: str, data: Union[str, bytes]) -> None:
embedded_files_names_dictionary.update(
{
NameObject(CA.NAMES): ArrayObject(
[createStringObject(filename), filespec]
[create_string_object(filename), filespec]
)
}
)
Expand Down Expand Up @@ -787,7 +799,7 @@ def add_metadata(self, infos: Dict[str, Any]) -> None:
"""
args = {}
for key, value in list(infos.items()):
args[NameObject(key)] = createStringObject(value)
args[NameObject(key)] = create_string_object(value)
self.get_object(self._info).update(args) # type: ignore

def addMetadata(self, infos: Dict[str, Any]) -> None: # pragma: no cover
Expand Down
87 changes: 62 additions & 25 deletions PyPDF2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
# POSSIBILITY OF SUCH DAMAGE.


"""Implementation of stream filters for PDF."""
"""
Implementation of stream filters for PDF.
See TABLE H.1 Abbreviations for standard filter names
"""
__author__ = "Mathieu Fenniak"
__author_email__ = "[email protected]"

Expand All @@ -43,7 +47,7 @@
except ImportError:
from typing_extensions import Literal # type: ignore[misc]

from ._utils import b_, ord_, paeth_predictor
from ._utils import b_, deprecate_with_replacement, ord_, paeth_predictor
from .constants import CcittFaxDecodeParameters as CCITT
from .constants import ColorSpaces
from .constants import FilterTypeAbbreviations as FTA
Expand Down Expand Up @@ -76,40 +80,45 @@ def compress(data: bytes) -> bytes:
class FlateDecode:
@staticmethod
def decode(
# TODO: PEP8
data: bytes,
decodeParms: Union[None, ArrayObject, DictionaryObject],
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
**kwargs: Any,
) -> bytes:
"""
:param data: flate-encoded data.
:param decodeParms: a dictionary of values, understanding the
:param decode_parms: a dictionary of values, understanding the
"/Predictor":<int> key only
:return: the flate-decoded data.
"""
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"]
str_data = decompress(data)
predictor = 1

if decodeParms:
if decode_parms:
try:
if isinstance(decodeParms, ArrayObject):
for decode_parm in decodeParms:
if isinstance(decode_parms, ArrayObject):
for decode_parm in decode_parms:
if "/Predictor" in decode_parm:
predictor = decode_parm["/Predictor"]
else:
predictor = decodeParms.get("/Predictor", 1)
predictor = decode_parms.get("/Predictor", 1)
except AttributeError:
pass # Usually an array with a null object was read
# predictor 1 == no predictor
if predictor != 1:
# The /Columns param. has 1 as the default value; see ISO 32000,
# §7.4.4.3 LZWDecode and FlateDecode Parameters, Table 8
if isinstance(decodeParms, ArrayObject):
if isinstance(decode_parms, ArrayObject):
columns = 1
for decode_parm in decodeParms:
for decode_parm in decode_parms:
if "/Columns" in decode_parm:
columns = decode_parm["/Columns"]
else:
columns = 1 if decodeParms is None else decodeParms.get(LZW.COLUMNS, 1)
columns = (
1 if decode_parms is None else decode_parms.get(LZW.COLUMNS, 1)
)

# PNG prediction:
if 10 <= predictor <= 15:
Expand Down Expand Up @@ -171,17 +180,20 @@ class ASCIIHexDecode:

@staticmethod
def decode(
# TODO: PEP8
data: str,
decodeParms: Union[None, ArrayObject, DictionaryObject] = None,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None, # noqa: F841
**kwargs: Any,
) -> str:
"""
:param data: a str sequence of hexadecimal-encoded values to be
converted into a base-7 ASCII string
:param decodeParms:
:param decode_parms:
:return: a string conversion in base-7 ASCII, where each of its values
v is such that 0 <= ord(v) <= 127.
"""
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"] # noqa: F841
retval = ""
hex_pair = ""
index = 0
Expand Down Expand Up @@ -288,16 +300,19 @@ def decode(self) -> str:

@staticmethod
def decode(
# TODO: PEP8
data: bytes,
decodeParms: Union[None, ArrayObject, DictionaryObject] = None,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
**kwargs: Any,
) -> str:
"""
:param data: ``bytes`` or ``str`` text to decode.
:param decodeParms: a dictionary of parameter values.
:param decode_parms: a dictionary of parameter values.
:return: decoded data.
:rtype: bytes
"""
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"] # noqa: F841
return LZWDecode.Decoder(data).decode()


Expand All @@ -307,8 +322,12 @@ class ASCII85Decode:
@staticmethod
def decode(
data: Union[str, bytes],
decodeParms: Union[None, ArrayObject, DictionaryObject] = None,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
**kwargs: Any,
) -> bytes:
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"] # noqa: F841
if isinstance(data, str):
data = data.encode("ascii")
group_index = b = 0
Expand All @@ -335,16 +354,26 @@ def decode(
class DCTDecode:
@staticmethod
def decode(
data: bytes, decodeParms: Union[None, ArrayObject, DictionaryObject] = None
data: bytes,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
**kwargs: Any,
) -> bytes:
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"] # noqa: F841
return data


class JPXDecode:
@staticmethod
def decode(
data: bytes, decodeParms: Union[None, ArrayObject, DictionaryObject] = None
data: bytes,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
**kwargs: Any,
) -> bytes:
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"] # noqa: F841
return data


Expand Down Expand Up @@ -403,11 +432,14 @@ def _get_parameters(
@staticmethod
def decode(
data: bytes,
# TODO: PEP8
decodeParms: Union[None, ArrayObject, DictionaryObject] = None,
decode_parms: Union[None, ArrayObject, DictionaryObject] = None,
height: int = 0,
**kwargs: Any,
) -> bytes:
parms = CCITTFaxDecode._get_parameters(decodeParms, height)
if "decodeParms" in kwargs: # pragma: no cover
deprecate_with_replacement("decodeParms", "parameters", "4.0.0")
decode_parms = kwargs["decodeParms"]
parms = CCITTFaxDecode._get_parameters(decode_parms, height)

img_size = len(data)
tiff_header_struct = "<2shlh" + "hhll" * 8 + "h"
Expand Down Expand Up @@ -457,7 +489,7 @@ def decode(
return tiff_header + data


def decodeStreamData(stream: Any) -> Union[str, bytes]: # utils.StreamObject
def decode_stream_data(stream: Any) -> Union[str, bytes]: # utils.StreamObject
filters = stream.get(SA.FILTER, ())

if len(filters) and not isinstance(filters[0], NameObject):
Expand Down Expand Up @@ -496,6 +528,11 @@ def decodeStreamData(stream: Any) -> Union[str, bytes]: # utils.StreamObject
return data


def decodeStreamData(stream: Any) -> Union[str, bytes]: # pragma: no cover
deprecate_with_replacement("decodeStreamData", "decode_stream_data", "4.0.0")
return decode_stream_data(stream)


def _xobj_to_image(x_object_obj: Dict[str, Any]) -> Tuple[Optional[str], bytes]:
"""
Users need to have the pillow package installed.
Expand Down
Loading

0 comments on commit 953a11d

Please sign in to comment.