Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Further improve exception traceback readability #90

Merged
merged 1 commit into from
Dec 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/PIL/ImImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,8 @@ def _open(self):

else:

raise SyntaxError(
"Syntax error in IM header: " + s.decode("ascii", "replace")
)
msg = "Syntax error in IM header: " + s.decode("ascii", "replace")
raise SyntaxError(msg)

if not n:
msg = "Not an IM file"
Expand Down
24 changes: 11 additions & 13 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2129,7 +2129,7 @@ def resize(self, size, resample=None, box=None, reducing_gap=None):
Resampling.BOX,
Resampling.HAMMING,
):
message = f"Unknown resampling filter ({resample})."
msg = f"Unknown resampling filter ({resample})."

filters = [
f"{filter[1]} ({filter[0]})"
Expand All @@ -2142,9 +2142,8 @@ def resize(self, size, resample=None, box=None, reducing_gap=None):
(Resampling.HAMMING, "Image.Resampling.HAMMING"),
)
]
raise ValueError(
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
)
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
raise ValueError(msg)

if reducing_gap is not None and reducing_gap < 1.0:
msg = "reducing_gap must be 1.0 or greater"
Expand Down Expand Up @@ -2764,13 +2763,13 @@ def __transformer(
Resampling.BICUBIC,
):
if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
message = {
msg = {
Resampling.BOX: "Image.Resampling.BOX",
Resampling.HAMMING: "Image.Resampling.HAMMING",
Resampling.LANCZOS: "Image.Resampling.LANCZOS",
}[resample] + f" ({resample}) cannot be used."
else:
message = f"Unknown resampling filter ({resample})."
msg = f"Unknown resampling filter ({resample})."

filters = [
f"{filter[1]} ({filter[0]})"
Expand All @@ -2780,9 +2779,8 @@ def __transformer(
(Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
)
]
raise ValueError(
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
)
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
raise ValueError(msg)

image.load()

Expand Down Expand Up @@ -3077,7 +3075,8 @@ def fromarray(obj, mode=None):
try:
mode, rawmode = _fromarray_typemap[typekey]
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:
rawmode = mode
if mode in ["1", "L", "I", "P", "F"]:
Expand Down Expand Up @@ -3276,9 +3275,8 @@ def _open_core(fp, filename, prefix, formats):
fp.close()
for message in accept_warnings:
warnings.warn(message)
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
)
msg = "cannot identify image file %r" % (filename if filename else fp)
raise UnidentifiedImageError(msg)


#
Expand Down
6 changes: 4 additions & 2 deletions src/PIL/ImageCms.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,8 @@ def buildTransform(
raise PyCMSError(msg)

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:
if not isinstance(inputProfile, ImageCmsProfile):
Expand Down Expand Up @@ -601,7 +602,8 @@ def buildProofTransform(
raise PyCMSError(msg)

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:
if not isinstance(inputProfile, ImageCmsProfile):
Expand Down
11 changes: 6 additions & 5 deletions src/PIL/ImageFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,13 @@

def raise_oserror(error):
try:
message = Image.core.getcodecstatus(error)
msg = Image.core.getcodecstatus(error)
except AttributeError:
message = ERRORS.get(error)
if not message:
message = f"decoder error {error}"
raise OSError(message + " when reading image file")
msg = ERRORS.get(error)
if not msg:
msg = f"decoder error {error}"
msg += " when reading image file"
raise OSError(msg)


def _tilesort(t):
Expand Down
3 changes: 2 additions & 1 deletion src/PIL/ImageMorph.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ def build_lut(self):
for p in self.patterns:
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
if not m:
raise Exception('Syntax error in pattern "' + p + '"')
msg = 'Syntax error in pattern "' + p + '"'
raise Exception(msg)
options = m.group(1)
pattern = m.group(2)
result = int(m.group(3))
Expand Down
11 changes: 6 additions & 5 deletions src/PIL/PdfParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,10 +817,10 @@ def get_value(cls, data, offset, expect_indirect=None, max_nesting=-1):
try:
stream_len = int(result[b"Length"])
except (TypeError, KeyError, ValueError) as e:
raise PdfFormatError(
"bad or missing Length in stream dict (%r)"
% result.get(b"Length", None)
) from e
msg = "bad or missing Length in stream dict (%r)" % result.get(
b"Length", None
)
raise PdfFormatError(msg) from e
stream_data = data[m.end() : m.end() + stream_len]
m = cls.re_stream_end.match(data, m.end() + stream_len)
check_format_condition(m, "stream end not found")
Expand Down Expand Up @@ -874,7 +874,8 @@ def get_value(cls, data, offset, expect_indirect=None, max_nesting=-1):
if m:
return cls.get_literal_string(data, m.end())
# 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(
rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"
Expand Down
6 changes: 4 additions & 2 deletions winbuild/build_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,8 @@ def extract_dep(url, filename):
raise RuntimeError(msg)
tgz.extractall(sources_dir)
else:
raise RuntimeError("Unknown archive type: " + filename)
msg = "Unknown archive type: " + filename
raise RuntimeError(msg)


def write_script(name, lines):
Expand Down Expand Up @@ -628,7 +629,8 @@ def build_pillow():
elif arg == "--srcdir":
sources_dir = os.path.sep + "src"
else:
raise ValueError("Unknown parameter: " + arg)
msg = "Unknown parameter: " + arg
raise ValueError(msg)

# dependency cache directory
os.makedirs(depends_dir, exist_ok=True)
Expand Down