From c41ec5b115142faceafef68d5a523f5e1d1ada17 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sun, 13 Jan 2019 09:17:51 -0800 Subject: [PATCH] Fix 'BytesWarning: Comparison between bytes and string' in PdfDict When bytes warnings are enabled with the '-b' argument, the PdfDict class would emit a warning. https://docs.python.org/3/using/cmdline.html#miscellaneous-options > -b > > Issue a warning when comparing bytes or bytearray with str or bytes > with int. Object attributes are always type str, so can safely encode them without a type check. Observe: $ python3 >>> o = object() >>> setattr(o, b'foo', b'bar') Traceback (most recent call last): File "", line 1, in TypeError: attribute name must be string, not 'bytes' --- src/PIL/PdfParser.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/PIL/PdfParser.py b/src/PIL/PdfParser.py index 7216e5b95..ca08bc864 100644 --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ -269,18 +269,13 @@ class PdfDict(UserDict): else: self.__dict__[key] = value else: - if isinstance(key, str): - key = key.encode("us-ascii") - self[key] = value + self[key.encode("us-ascii")] = value def __getattr__(self, key): try: - value = self[key] + value = self[key.encode("us-ascii")] except KeyError: - try: - value = self[key.encode("us-ascii")] - except KeyError: - raise AttributeError(key) + raise AttributeError(key) if isinstance(value, bytes): value = decode_text(value) if key.endswith("Date"):