Skip to content

Commit 9ded242

Browse files
authored
Merge pull request #296 from bgilbert/chaining
Include all `LoadLibrary()` failures in exception chain
2 parents ece4466 + d6fb5c0 commit 9ded242

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
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: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -72,30 +72,32 @@ def _load_library() -> CDLL:
7272
pass
7373

7474
def try_load(names: list[str]) -> CDLL:
75-
for name in names:
76-
try:
77-
return cdll.LoadLibrary(name)
78-
except OSError:
79-
if name == names[-1]:
80-
raise
81-
else:
82-
raise ValueError('No library names specified')
75+
try:
76+
return cdll.LoadLibrary(names[0])
77+
except OSError:
78+
remaining = names[1:]
79+
if remaining:
80+
# handle recursively so implicit exception chaining captures
81+
# all the failures
82+
return try_load(remaining)
83+
else:
84+
raise
8385

8486
if platform.system() == 'Windows':
8587
try:
8688
return try_load(['libopenslide-1.dll', 'libopenslide-0.dll'])
87-
except FileNotFoundError:
89+
except FileNotFoundError as exc:
8890
raise ModuleNotFoundError(
8991
"Couldn't locate OpenSlide DLL. "
9092
"Try `pip install openslide-bin`, "
9193
"or if you're using an OpenSlide binary package, "
9294
"ensure you've called os.add_dll_directory(). "
9395
"https://openslide.org/api/python/#installing"
94-
)
96+
) from exc
9597
elif platform.system() == 'Darwin':
9698
try:
9799
return try_load(['libopenslide.1.dylib', 'libopenslide.0.dylib'])
98-
except OSError:
100+
except OSError as exc:
99101
# MacPorts doesn't add itself to the dyld search path, but
100102
# does add itself to the find_library() search path
101103
# (DEFAULT_LIBRARY_FALLBACK in ctypes.macholib.dyld).
@@ -107,17 +109,17 @@ def try_load(names: list[str]) -> CDLL:
107109
"Couldn't locate OpenSlide dylib. "
108110
"Try `pip install openslide-bin`. "
109111
"https://openslide.org/api/python/#installing"
110-
)
112+
) from exc
111113
return cdll.LoadLibrary(lib)
112114
else:
113115
try:
114116
return try_load(['libopenslide.so.1', 'libopenslide.so.0'])
115-
except OSError:
117+
except OSError as exc:
116118
raise ModuleNotFoundError(
117119
"Couldn't locate OpenSlide shared library. "
118120
"Try `pip install openslide-bin`. "
119121
"https://openslide.org/api/python/#installing"
120-
)
122+
) from exc
121123

122124

123125
_lib = _load_library()

0 commit comments

Comments
 (0)