Skip to content

Commit 343d435

Browse files
committed
Use explicit exception chaining when converting exception types
This changes Python's exception chain reporting to make it clear that the new exception was not an unrelated failure while handling the original one, but rather the direct cause of it. Signed-off-by: Benjamin Gilbert <[email protected]>
1 parent ece4466 commit 343d435

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

openslide/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,8 @@ def set_cache(self, cache: OpenSlideCache) -> None:
293293
cache: an OpenSlideCache object."""
294294
try:
295295
llcache = cache._openslide_cache
296-
except AttributeError:
297-
raise TypeError('Not a cache object')
296+
except AttributeError as exc:
297+
raise TypeError('Not a cache object') from exc
298298
lowlevel.set_cache(self._osr, llcache)
299299

300300

openslide/lowlevel.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,18 +84,18 @@ def try_load(names: list[str]) -> CDLL:
8484
if platform.system() == 'Windows':
8585
try:
8686
return try_load(['libopenslide-1.dll', 'libopenslide-0.dll'])
87-
except FileNotFoundError:
87+
except FileNotFoundError as exc:
8888
raise ModuleNotFoundError(
8989
"Couldn't locate OpenSlide DLL. "
9090
"Try `pip install openslide-bin`, "
9191
"or if you're using an OpenSlide binary package, "
9292
"ensure you've called os.add_dll_directory(). "
9393
"https://openslide.org/api/python/#installing"
94-
)
94+
) from exc
9595
elif platform.system() == 'Darwin':
9696
try:
9797
return try_load(['libopenslide.1.dylib', 'libopenslide.0.dylib'])
98-
except OSError:
98+
except OSError as exc:
9999
# MacPorts doesn't add itself to the dyld search path, but
100100
# does add itself to the find_library() search path
101101
# (DEFAULT_LIBRARY_FALLBACK in ctypes.macholib.dyld).
@@ -107,17 +107,17 @@ def try_load(names: list[str]) -> CDLL:
107107
"Couldn't locate OpenSlide dylib. "
108108
"Try `pip install openslide-bin`. "
109109
"https://openslide.org/api/python/#installing"
110-
)
110+
) from exc
111111
return cdll.LoadLibrary(lib)
112112
else:
113113
try:
114114
return try_load(['libopenslide.so.1', 'libopenslide.so.0'])
115-
except OSError:
115+
except OSError as exc:
116116
raise ModuleNotFoundError(
117117
"Couldn't locate OpenSlide shared library. "
118118
"Try `pip install openslide-bin`. "
119119
"https://openslide.org/api/python/#installing"
120-
)
120+
) from exc
121121

122122

123123
_lib = _load_library()

0 commit comments

Comments
 (0)