Skip to content

Commit f8087db

Browse files
committed
fix: use importlib to load bindings module explicitly
The wheel structure has both isomdl_uniffi.py (module) and isomdl_uniffi/ (package containing the .so file). Python prefers packages over modules, so the standard import statement would find the empty package __init__.py instead of the bindings. This fix uses importlib.util to explicitly load the .py file by path. Signed-off-by: Adam Burdett <burdettadam@gmail.com>
1 parent 9e73da5 commit f8087db

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

python/isomdl_uniffi/__init__.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,37 @@
1414

1515
__version__ = "0.1.0"
1616

17-
# Import the main module - try multiple paths to handle different wheel structures
17+
import importlib.util
18+
import os
19+
import sys
20+
1821
_imported = False
1922
_import_error = None
2023

21-
# Try: isomdl_uniffi/isomdl_uniffi.py (generated by maturin for mixed projects)
22-
if not _imported:
23-
try:
24-
from .isomdl_uniffi import *
25-
_imported = True
26-
except ImportError as e:
27-
_import_error = e
24+
# The wheel structure has both:
25+
# - isomdl_uniffi/isomdl_uniffi.py (the Python bindings)
26+
# - isomdl_uniffi/isomdl_uniffi/ (directory containing the .so)
27+
# Python prefers packages over modules, so we must explicitly load the .py file.
2828

29-
# Try: isomdl_uniffi/isomdl_uniffi/isomdl_uniffi.py (nested structure)
30-
if not _imported:
29+
_module_dir = os.path.dirname(os.path.abspath(__file__))
30+
_bindings_path = os.path.join(_module_dir, "isomdl_uniffi.py")
31+
32+
if os.path.exists(_bindings_path):
3133
try:
32-
from .isomdl_uniffi.isomdl_uniffi import *
33-
_imported = True
34-
except ImportError:
35-
pass
34+
spec = importlib.util.spec_from_file_location(
35+
"_isomdl_uniffi_bindings", _bindings_path
36+
)
37+
if spec and spec.loader:
38+
_bindings_module = importlib.util.module_from_spec(spec)
39+
sys.modules["_isomdl_uniffi_bindings"] = _bindings_module
40+
spec.loader.exec_module(_bindings_module)
41+
# Export everything from the bindings module
42+
_all_exports = getattr(_bindings_module, "__all__", [])
43+
for _name in _all_exports:
44+
globals()[_name] = getattr(_bindings_module, _name)
45+
_imported = True
46+
except Exception as e:
47+
_import_error = e
3648

3749
if not _imported:
3850
raise ImportError(
@@ -41,3 +53,4 @@
4153
f"Please run './python/precommit/build-bindings.sh' first. "
4254
f"Original error: {_import_error}"
4355
)
56+

0 commit comments

Comments
 (0)