Skip to content

Commit

Permalink
Merge pull request #296 from bgilbert/chaining
Browse files Browse the repository at this point in the history
Include all `LoadLibrary()` failures in exception chain
  • Loading branch information
bgilbert authored Oct 28, 2024
2 parents ece4466 + d6fb5c0 commit 9ded242
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
4 changes: 2 additions & 2 deletions openslide/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,8 @@ def set_cache(self, cache: OpenSlideCache) -> None:
cache: an OpenSlideCache object."""
try:
llcache = cache._openslide_cache
except AttributeError:
raise TypeError('Not a cache object')
except AttributeError as exc:
raise TypeError('Not a cache object') from exc
lowlevel.set_cache(self._osr, llcache)


Expand Down
30 changes: 16 additions & 14 deletions openslide/lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,30 +72,32 @@ def _load_library() -> CDLL:
pass

def try_load(names: list[str]) -> CDLL:
for name in names:
try:
return cdll.LoadLibrary(name)
except OSError:
if name == names[-1]:
raise
else:
raise ValueError('No library names specified')
try:
return cdll.LoadLibrary(names[0])
except OSError:
remaining = names[1:]
if remaining:
# handle recursively so implicit exception chaining captures
# all the failures
return try_load(remaining)
else:
raise

if platform.system() == 'Windows':
try:
return try_load(['libopenslide-1.dll', 'libopenslide-0.dll'])
except FileNotFoundError:
except FileNotFoundError as exc:
raise ModuleNotFoundError(
"Couldn't locate OpenSlide DLL. "
"Try `pip install openslide-bin`, "
"or if you're using an OpenSlide binary package, "
"ensure you've called os.add_dll_directory(). "
"https://openslide.org/api/python/#installing"
)
) from exc
elif platform.system() == 'Darwin':
try:
return try_load(['libopenslide.1.dylib', 'libopenslide.0.dylib'])
except OSError:
except OSError as exc:
# MacPorts doesn't add itself to the dyld search path, but
# does add itself to the find_library() search path
# (DEFAULT_LIBRARY_FALLBACK in ctypes.macholib.dyld).
Expand All @@ -107,17 +109,17 @@ def try_load(names: list[str]) -> CDLL:
"Couldn't locate OpenSlide dylib. "
"Try `pip install openslide-bin`. "
"https://openslide.org/api/python/#installing"
)
) from exc
return cdll.LoadLibrary(lib)
else:
try:
return try_load(['libopenslide.so.1', 'libopenslide.so.0'])
except OSError:
except OSError as exc:
raise ModuleNotFoundError(
"Couldn't locate OpenSlide shared library. "
"Try `pip install openslide-bin`. "
"https://openslide.org/api/python/#installing"
)
) from exc


_lib = _load_library()
Expand Down

0 comments on commit 9ded242

Please sign in to comment.