Further improve exception traceback readability

This commit is contained in:
Andrew Murray 2022-12-30 14:24:28 +11:00
parent 2ae55ccbda
commit 68fdd2a9e7
7 changed files with 35 additions and 31 deletions

View File

@ -201,9 +201,8 @@ class ImImageFile(ImageFile.ImageFile):
else: else:
raise SyntaxError( msg = "Syntax error in IM header: " + s.decode("ascii", "replace")
"Syntax error in IM header: " + s.decode("ascii", "replace") raise SyntaxError(msg)
)
if not n: if not n:
msg = "Not an IM file" msg = "Not an IM file"

View File

@ -2129,7 +2129,7 @@ class Image:
Resampling.BOX, Resampling.BOX,
Resampling.HAMMING, Resampling.HAMMING,
): ):
message = f"Unknown resampling filter ({resample})." msg = f"Unknown resampling filter ({resample})."
filters = [ filters = [
f"{filter[1]} ({filter[0]})" f"{filter[1]} ({filter[0]})"
@ -2142,9 +2142,8 @@ class Image:
(Resampling.HAMMING, "Image.Resampling.HAMMING"), (Resampling.HAMMING, "Image.Resampling.HAMMING"),
) )
] ]
raise ValueError( msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg)
)
if reducing_gap is not None and reducing_gap < 1.0: if reducing_gap is not None and reducing_gap < 1.0:
msg = "reducing_gap must be 1.0 or greater" msg = "reducing_gap must be 1.0 or greater"
@ -2764,13 +2763,13 @@ class Image:
Resampling.BICUBIC, Resampling.BICUBIC,
): ):
if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
message = { msg = {
Resampling.BOX: "Image.Resampling.BOX", Resampling.BOX: "Image.Resampling.BOX",
Resampling.HAMMING: "Image.Resampling.HAMMING", Resampling.HAMMING: "Image.Resampling.HAMMING",
Resampling.LANCZOS: "Image.Resampling.LANCZOS", Resampling.LANCZOS: "Image.Resampling.LANCZOS",
}[resample] + f" ({resample}) cannot be used." }[resample] + f" ({resample}) cannot be used."
else: else:
message = f"Unknown resampling filter ({resample})." msg = f"Unknown resampling filter ({resample})."
filters = [ filters = [
f"{filter[1]} ({filter[0]})" f"{filter[1]} ({filter[0]})"
@ -2780,9 +2779,8 @@ class Image:
(Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
) )
] ]
raise ValueError( msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] raise ValueError(msg)
)
image.load() image.load()
@ -3077,7 +3075,8 @@ def fromarray(obj, mode=None):
try: try:
mode, rawmode = _fromarray_typemap[typekey] mode, rawmode = _fromarray_typemap[typekey]
except KeyError as e: except KeyError as e:
raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e msg = "Cannot handle this data type: %s, %s" % typekey
raise TypeError(msg) from e
else: else:
rawmode = mode rawmode = mode
if mode in ["1", "L", "I", "P", "F"]: if mode in ["1", "L", "I", "P", "F"]:
@ -3276,9 +3275,8 @@ def open(fp, mode="r", formats=None):
fp.close() fp.close()
for message in accept_warnings: for message in accept_warnings:
warnings.warn(message) warnings.warn(message)
raise UnidentifiedImageError( msg = "cannot identify image file %r" % (filename if filename else fp)
"cannot identify image file %r" % (filename if filename else fp) raise UnidentifiedImageError(msg)
)
# #

View File

@ -498,7 +498,8 @@ def buildTransform(
raise PyCMSError(msg) raise PyCMSError(msg)
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG) msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
raise PyCMSError(msg)
try: try:
if not isinstance(inputProfile, ImageCmsProfile): if not isinstance(inputProfile, ImageCmsProfile):
@ -601,7 +602,8 @@ def buildProofTransform(
raise PyCMSError(msg) raise PyCMSError(msg)
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG) msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
raise PyCMSError(msg)
try: try:
if not isinstance(inputProfile, ImageCmsProfile): if not isinstance(inputProfile, ImageCmsProfile):

View File

@ -63,12 +63,13 @@ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
def raise_oserror(error): def raise_oserror(error):
try: try:
message = Image.core.getcodecstatus(error) msg = Image.core.getcodecstatus(error)
except AttributeError: except AttributeError:
message = ERRORS.get(error) msg = ERRORS.get(error)
if not message: if not msg:
message = f"decoder error {error}" msg = f"decoder error {error}"
raise OSError(message + " when reading image file") msg += " when reading image file"
raise OSError(msg)
def _tilesort(t): def _tilesort(t):

View File

@ -146,7 +146,8 @@ class LutBuilder:
for p in self.patterns: for p in self.patterns:
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", "")) m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
if not m: if not m:
raise Exception('Syntax error in pattern "' + p + '"') msg = 'Syntax error in pattern "' + p + '"'
raise Exception(msg)
options = m.group(1) options = m.group(1)
pattern = m.group(2) pattern = m.group(2)
result = int(m.group(3)) result = int(m.group(3))

View File

@ -817,10 +817,10 @@ class PdfParser:
try: try:
stream_len = int(result[b"Length"]) stream_len = int(result[b"Length"])
except (TypeError, KeyError, ValueError) as e: except (TypeError, KeyError, ValueError) as e:
raise PdfFormatError( msg = "bad or missing Length in stream dict (%r)" % result.get(
"bad or missing Length in stream dict (%r)" b"Length", None
% result.get(b"Length", None) )
) from e raise PdfFormatError(msg) from e
stream_data = data[m.end() : m.end() + stream_len] stream_data = data[m.end() : m.end() + stream_len]
m = cls.re_stream_end.match(data, m.end() + stream_len) m = cls.re_stream_end.match(data, m.end() + stream_len)
check_format_condition(m, "stream end not found") check_format_condition(m, "stream end not found")
@ -874,7 +874,8 @@ class PdfParser:
if m: if m:
return cls.get_literal_string(data, m.end()) return cls.get_literal_string(data, m.end())
# return None, offset # fallback (only for debugging) # return None, offset # fallback (only for debugging)
raise PdfFormatError("unrecognized object: " + repr(data[offset : offset + 32])) msg = "unrecognized object: " + repr(data[offset : offset + 32])
raise PdfFormatError(msg)
re_lit_str_token = re.compile( re_lit_str_token = re.compile(
rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))" rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"

View File

@ -491,7 +491,8 @@ def extract_dep(url, filename):
raise RuntimeError(msg) raise RuntimeError(msg)
tgz.extractall(sources_dir) tgz.extractall(sources_dir)
else: else:
raise RuntimeError("Unknown archive type: " + filename) msg = "Unknown archive type: " + filename
raise RuntimeError(msg)
def write_script(name, lines): def write_script(name, lines):
@ -628,7 +629,8 @@ if __name__ == "__main__":
elif arg == "--srcdir": elif arg == "--srcdir":
sources_dir = os.path.sep + "src" sources_dir = os.path.sep + "src"
else: else:
raise ValueError("Unknown parameter: " + arg) msg = "Unknown parameter: " + arg
raise ValueError(msg)
# dependency cache directory # dependency cache directory
os.makedirs(depends_dir, exist_ok=True) os.makedirs(depends_dir, exist_ok=True)