Skip to content

Commit 70b2782

Browse files
committed
Improve exception traceback readability
1 parent 2755e0f commit 70b2782

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+861
-485
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ repos:
3535
rev: 6.0.0
3636
hooks:
3737
- id: flake8
38-
additional_dependencies: [flake8-2020, flake8-implicit-str-concat]
38+
additional_dependencies:
39+
[flake8-2020, flake8-errmsg, flake8-implicit-str-concat]
3940

4041
- repo: https://github.com/pre-commit/pygrep-hooks
4142
rev: v1.9.0

docs/example/DdsImagePlugin.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -211,13 +211,16 @@ class DdsImageFile(ImageFile.ImageFile):
211211

212212
def _open(self):
213213
if not _accept(self.fp.read(4)):
214-
raise SyntaxError("not a DDS file")
214+
msg = "not a DDS file"
215+
raise SyntaxError(msg)
215216
(header_size,) = struct.unpack("<I", self.fp.read(4))
216217
if header_size != 124:
217-
raise OSError(f"Unsupported header size {repr(header_size)}")
218+
msg = f"Unsupported header size {repr(header_size)}"
219+
raise OSError(msg)
218220
header_bytes = self.fp.read(header_size - 4)
219221
if len(header_bytes) != 120:
220-
raise OSError(f"Incomplete header: {len(header_bytes)} bytes")
222+
msg = f"Incomplete header: {len(header_bytes)} bytes"
223+
raise OSError(msg)
221224
header = BytesIO(header_bytes)
222225

223226
flags, height, width = struct.unpack("<3I", header.read(12))
@@ -237,7 +240,8 @@ def _open(self):
237240
elif fourcc == b"DXT5":
238241
self.decoder = "DXT5"
239242
else:
240-
raise NotImplementedError(f"Unimplemented pixel format {fourcc}")
243+
msg = f"Unimplemented pixel format {fourcc}"
244+
raise NotImplementedError(msg)
241245

242246
self.tile = [(self.decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
243247

@@ -252,7 +256,8 @@ def decode(self, buffer):
252256
try:
253257
self.set_as_raw(_dxt1(self.fd, self.state.xsize, self.state.ysize))
254258
except struct.error as e:
255-
raise OSError("Truncated DDS file") from e
259+
msg = "Truncated DDS file"
260+
raise OSError(msg) from e
256261
return -1, 0
257262

258263

@@ -263,7 +268,8 @@ def decode(self, buffer):
263268
try:
264269
self.set_as_raw(_dxt5(self.fd, self.state.xsize, self.state.ysize))
265270
except struct.error as e:
266-
raise OSError("Truncated DDS file") from e
271+
msg = "Truncated DDS file"
272+
raise OSError(msg) from e
267273
return -1, 0
268274

269275

docs/handbook/writing-your-own-image-plugin.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ true color.
7878
elif bits == 24:
7979
self.mode = "RGB"
8080
else:
81-
raise SyntaxError("unknown number of bits")
81+
msg = "unknown number of bits"
82+
raise SyntaxError(msg)
8283

8384
# data descriptor
8485
self.tile = [("raw", (0, 0) + self.size, 128, (self.mode, 0, 1))]

setup.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -362,15 +362,15 @@ def finalize_options(self):
362362
self.feature.required.discard(x)
363363
_dbg("Disabling %s", x)
364364
if getattr(self, f"enable_{x}"):
365-
raise ValueError(
366-
f"Conflicting options: --enable-{x} and --disable-{x}"
367-
)
365+
msg = f"Conflicting options: --enable-{x} and --disable-{x}"
366+
raise ValueError(msg)
368367
if x == "freetype":
369368
_dbg("--disable-freetype implies --disable-raqm")
370369
if getattr(self, "enable_raqm"):
371-
raise ValueError(
370+
msg = (
372371
"Conflicting options: --enable-raqm and --disable-freetype"
373372
)
373+
raise ValueError(msg)
374374
setattr(self, "disable_raqm", True)
375375
if getattr(self, f"enable_{x}"):
376376
_dbg("Requiring %s", x)
@@ -381,13 +381,11 @@ def finalize_options(self):
381381
for x in ("raqm", "fribidi"):
382382
if getattr(self, f"vendor_{x}"):
383383
if getattr(self, "disable_raqm"):
384-
raise ValueError(
385-
f"Conflicting options: --vendor-{x} and --disable-raqm"
386-
)
384+
msg = f"Conflicting options: --vendor-{x} and --disable-raqm"
385+
raise ValueError(msg)
387386
if x == "fribidi" and not getattr(self, "vendor_raqm"):
388-
raise ValueError(
389-
f"Conflicting options: --vendor-{x} and not --vendor-raqm"
390-
)
387+
msg = f"Conflicting options: --vendor-{x} and not --vendor-raqm"
388+
raise ValueError(msg)
391389
_dbg("Using vendored version of %s", x)
392390
self.feature.vendor.add(x)
393391

src/PIL/BdfFontFile.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,8 @@ def __init__(self, fp):
8686

8787
s = fp.readline()
8888
if s[:13] != b"STARTFONT 2.1":
89-
raise SyntaxError("not a valid BDF file")
89+
msg = "not a valid BDF file"
90+
raise SyntaxError(msg)
9091

9192
props = {}
9293
comments = []

src/PIL/BlpImagePlugin.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ def __getattr__(name):
6565
if name in enum.__members__:
6666
deprecate(f"{prefix}{name}", 10, f"{enum.__name__}.{name}")
6767
return enum[name]
68-
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
68+
msg = f"module '{__name__}' has no attribute '{name}'"
69+
raise AttributeError(msg)
6970

7071

7172
def unpack_565(i):
@@ -278,7 +279,8 @@ def _open(self):
278279
if self.magic in (b"BLP1", b"BLP2"):
279280
decoder = self.magic.decode()
280281
else:
281-
raise BLPFormatError(f"Bad BLP magic {repr(self.magic)}")
282+
msg = f"Bad BLP magic {repr(self.magic)}"
283+
raise BLPFormatError(msg)
282284

283285
self.mode = "RGBA" if self._blp_alpha_depth else "RGB"
284286
self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
@@ -292,7 +294,8 @@ def decode(self, buffer):
292294
self._read_blp_header()
293295
self._load()
294296
except struct.error as e:
295-
raise OSError("Truncated BLP file") from e
297+
msg = "Truncated BLP file"
298+
raise OSError(msg) from e
296299
return -1, 0
297300

298301
def _read_blp_header(self):
@@ -354,13 +357,11 @@ def _load(self):
354357
data = self._read_bgra(palette)
355358
self.set_as_raw(bytes(data))
356359
else:
357-
raise BLPFormatError(
358-
f"Unsupported BLP encoding {repr(self._blp_encoding)}"
359-
)
360+
msg = f"Unsupported BLP encoding {repr(self._blp_encoding)}"
361+
raise BLPFormatError(msg)
360362
else:
361-
raise BLPFormatError(
362-
f"Unsupported BLP compression {repr(self._blp_encoding)}"
363-
)
363+
msg = f"Unsupported BLP compression {repr(self._blp_encoding)}"
364+
raise BLPFormatError(msg)
364365

365366
def _decode_jpeg_stream(self):
366367
from .JpegImagePlugin import JpegImageFile
@@ -415,16 +416,15 @@ def _load(self):
415416
for d in decode_dxt5(self._safe_read(linesize)):
416417
data += d
417418
else:
418-
raise BLPFormatError(
419-
f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
420-
)
419+
msg = f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
420+
raise BLPFormatError(msg)
421421
else:
422-
raise BLPFormatError(f"Unknown BLP encoding {repr(self._blp_encoding)}")
422+
msg = f"Unknown BLP encoding {repr(self._blp_encoding)}"
423+
raise BLPFormatError(msg)
423424

424425
else:
425-
raise BLPFormatError(
426-
f"Unknown BLP compression {repr(self._blp_compression)}"
427-
)
426+
msg = f"Unknown BLP compression {repr(self._blp_compression)}"
427+
raise BLPFormatError(msg)
428428

429429
self.set_as_raw(bytes(data))
430430

@@ -460,7 +460,8 @@ def encode(self, bufsize):
460460

461461
def _save(im, fp, filename, save_all=False):
462462
if im.mode != "P":
463-
raise ValueError("Unsupported BLP image mode")
463+
msg = "Unsupported BLP image mode"
464+
raise ValueError(msg)
464465

465466
magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
466467
fp.write(magic)

src/PIL/BmpImagePlugin.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ def _bitmap(self, header=0, offset=0):
146146
file_info["a_mask"],
147147
)
148148
else:
149-
raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
149+
msg = f"Unsupported BMP header type ({file_info['header_size']})"
150+
raise OSError(msg)
150151

151152
# ------------------ Special case : header is reported 40, which
152153
# ---------------------- is shorter than real size for bpp >= 16
@@ -164,7 +165,8 @@ def _bitmap(self, header=0, offset=0):
164165
# ---------------------- Check bit depth for unusual unsupported values
165166
self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
166167
if self.mode is None:
167-
raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
168+
msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
169+
raise OSError(msg)
168170

169171
# ---------------- Process BMP with Bitfields compression (not palette)
170172
decoder_name = "raw"
@@ -205,23 +207,27 @@ def _bitmap(self, header=0, offset=0):
205207
):
206208
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
207209
else:
208-
raise OSError("Unsupported BMP bitfields layout")
210+
msg = "Unsupported BMP bitfields layout"
211+
raise OSError(msg)
209212
else:
210-
raise OSError("Unsupported BMP bitfields layout")
213+
msg = "Unsupported BMP bitfields layout"
214+
raise OSError(msg)
211215
elif file_info["compression"] == self.RAW:
212216
if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
213217
raw_mode, self.mode = "BGRA", "RGBA"
214218
elif file_info["compression"] in (self.RLE8, self.RLE4):
215219
decoder_name = "bmp_rle"
216220
else:
217-
raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
221+
msg = f"Unsupported BMP compression ({file_info['compression']})"
222+
raise OSError(msg)
218223

219224
# --------------- Once the header is processed, process the palette/LUT
220225
if self.mode == "P": # Paletted for 1, 4 and 8 bit images
221226

222227
# ---------------------------------------------------- 1-bit images
223228
if not (0 < file_info["colors"] <= 65536):
224-
raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
229+
msg = f"Unsupported BMP Palette size ({file_info['colors']})"
230+
raise OSError(msg)
225231
else:
226232
padding = file_info["palette_padding"]
227233
palette = read(padding * file_info["colors"])
@@ -271,7 +277,8 @@ def _open(self):
271277
head_data = self.fp.read(14)
272278
# choke if the file does not have the required magic bytes
273279
if not _accept(head_data):
274-
raise SyntaxError("Not a BMP file")
280+
msg = "Not a BMP file"
281+
raise SyntaxError(msg)
275282
# read the start position of the BMP image data (u32)
276283
offset = i32(head_data, 10)
277284
# load bitmap information (offset=raster info)
@@ -383,7 +390,8 @@ def _save(im, fp, filename, bitmap_header=True):
383390
try:
384391
rawmode, bits, colors = SAVE[im.mode]
385392
except KeyError as e:
386-
raise OSError(f"cannot write mode {im.mode} as BMP") from e
393+
msg = f"cannot write mode {im.mode} as BMP"
394+
raise OSError(msg) from e
387395

388396
info = im.encoderinfo
389397

@@ -411,7 +419,8 @@ def _save(im, fp, filename, bitmap_header=True):
411419
offset = 14 + header + colors * 4
412420
file_size = offset + image
413421
if file_size > 2**32 - 1:
414-
raise ValueError("File size is too large for the BMP format")
422+
msg = "File size is too large for the BMP format"
423+
raise ValueError(msg)
415424
fp.write(
416425
b"BM" # file type (magic)
417426
+ o32(file_size) # file size

src/PIL/BufrStubImagePlugin.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def _open(self):
4242
offset = self.fp.tell()
4343

4444
if not _accept(self.fp.read(4)):
45-
raise SyntaxError("Not a BUFR file")
45+
msg = "Not a BUFR file"
46+
raise SyntaxError(msg)
4647

4748
self.fp.seek(offset)
4849

@@ -60,7 +61,8 @@ def _load(self):
6061

6162
def _save(im, fp, filename):
6263
if _handler is None or not hasattr(_handler, "save"):
63-
raise OSError("BUFR save handler not installed")
64+
msg = "BUFR save handler not installed"
65+
raise OSError(msg)
6466
_handler.save(im, fp, filename)
6567

6668

src/PIL/CurImagePlugin.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ def _open(self):
4343
# check magic
4444
s = self.fp.read(6)
4545
if not _accept(s):
46-
raise SyntaxError("not a CUR file")
46+
msg = "not a CUR file"
47+
raise SyntaxError(msg)
4748

4849
# pick the largest cursor in the file
4950
m = b""
@@ -54,7 +55,8 @@ def _open(self):
5455
elif s[0] > m[0] and s[1] > m[1]:
5556
m = s
5657
if not m:
57-
raise TypeError("No cursors were found")
58+
msg = "No cursors were found"
59+
raise TypeError(msg)
5860

5961
# load as bitmap
6062
self._bitmap(i32(m, 12) + offset)

src/PIL/DcxImagePlugin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ def _open(self):
4747
# Header
4848
s = self.fp.read(4)
4949
if not _accept(s):
50-
raise SyntaxError("not a DCX file")
50+
msg = "not a DCX file"
51+
raise SyntaxError(msg)
5152

5253
# Component directory
5354
self._offset = []

0 commit comments

Comments
 (0)