Skip to content

Commit 9d06a40

Browse files
committed
lowlevel: move library loading into a helper function
This allows us to have variables that don't pollute the module namespace. Signed-off-by: Benjamin Gilbert <[email protected]>
1 parent 4cc1a0f commit 9d06a40

File tree

1 file changed

+35
-30
lines changed

1 file changed

+35
-30
lines changed

openslide/lowlevel.py

Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -49,39 +49,44 @@
4949

5050
from . import _convert
5151

52-
if platform.system() == 'Windows':
53-
try:
54-
_lib = cdll.LoadLibrary('libopenslide-0.dll')
55-
except FileNotFoundError:
56-
import os
5752

58-
if hasattr(os, 'add_dll_directory'):
59-
# Python >= 3.8
60-
_admonition = 'Did you call os.add_dll_directory()?'
61-
else:
62-
_admonition = 'Did you add OpenSlide to PATH?'
63-
raise ModuleNotFoundError(
64-
f"Couldn't locate OpenSlide DLL. {_admonition} "
65-
"https://openslide.org/api/python/#installing"
66-
)
67-
elif platform.system() == 'Darwin':
68-
try:
69-
_lib = cdll.LoadLibrary('libopenslide.0.dylib')
70-
except OSError:
71-
# MacPorts doesn't add itself to the dyld search path, but
72-
# does add itself to the find_library() search path
73-
# (DEFAULT_LIBRARY_FALLBACK in ctypes.macholib.dyld).
74-
import ctypes.util
75-
76-
_lib = ctypes.util.find_library('openslide')
77-
if _lib is None:
53+
def _load_library():
54+
if platform.system() == 'Windows':
55+
try:
56+
return cdll.LoadLibrary('libopenslide-0.dll')
57+
except FileNotFoundError:
58+
import os
59+
60+
if hasattr(os, 'add_dll_directory'):
61+
# Python >= 3.8
62+
admonition = 'Did you call os.add_dll_directory()?'
63+
else:
64+
admonition = 'Did you add OpenSlide to PATH?'
7865
raise ModuleNotFoundError(
79-
"Couldn't locate OpenSlide dylib. Is OpenSlide installed "
80-
"correctly? https://openslide.org/api/python/#installing"
66+
f"Couldn't locate OpenSlide DLL. {admonition} "
67+
"https://openslide.org/api/python/#installing"
8168
)
82-
_lib = cdll.LoadLibrary(_lib)
83-
else:
84-
_lib = cdll.LoadLibrary('libopenslide.so.0')
69+
elif platform.system() == 'Darwin':
70+
try:
71+
return cdll.LoadLibrary('libopenslide.0.dylib')
72+
except OSError:
73+
# MacPorts doesn't add itself to the dyld search path, but
74+
# does add itself to the find_library() search path
75+
# (DEFAULT_LIBRARY_FALLBACK in ctypes.macholib.dyld).
76+
import ctypes.util
77+
78+
lib = ctypes.util.find_library('openslide')
79+
if lib is None:
80+
raise ModuleNotFoundError(
81+
"Couldn't locate OpenSlide dylib. Is OpenSlide installed "
82+
"correctly? https://openslide.org/api/python/#installing"
83+
)
84+
return cdll.LoadLibrary(lib)
85+
else:
86+
return cdll.LoadLibrary('libopenslide.so.0')
87+
88+
89+
_lib = _load_library()
8590

8691

8792
class OpenSlideError(Exception):

0 commit comments

Comments
 (0)