Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Fix lazy package initialization during submodule imports (#10520)

Isaac Miller3c584233b093
diff --git a/dspy/utils/lazy_import.py b/dspy/utils/lazy_import.py
index 2a9314727..8d89a35d8 100644
--- a/dspy/utils/lazy_import.py
+++ b/dspy/utils/lazy_import.py
@@ -92,28 +92,12 @@ class _LazyModule(types.ModuleType):
self.__package__ = spec.parent
if spec.submodule_search_locations is not None:
self.__path__ = spec.submodule_search_locations
- self._dspy_lazy_spec = spec
self._dspy_lazy_lock = lock
def _load(self) -> types.ModuleType:
- # The proxy starts in sys.modules, then the first attribute access swaps in and executes the real module under
- # the per-module lock. If import fails, restore the proxy so later accesses can retry and still share the lock.
- # Return sys.modules after execution because a module may replace itself while importing.
- module_name = self.__name__
+ # Keep proxies out of sys.modules so Python owns package initialization and submodule imports.
with self._dspy_lazy_lock:
- loaded = sys.modules.get(module_name)
- if loaded is not None and loaded is not self:
- return loaded
-
- spec = self._dspy_lazy_spec
- module = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = module
- try:
- spec.loader.exec_module(module)
- except Exception:
- sys.modules[module_name] = self
- raise
- return sys.modules.get(module_name, module)
+ return importlib.import_module(self.__name__)
def __getattr__(self, attr: str) -> Any:
return getattr(self._load(), attr)
@@ -185,6 +169,4 @@ def require(module: str, *, extra: str | None = None, feature: str | None = None
if module in sys.modules:
return sys.modules[module]
- mod = _LazyModule(module, spec, lock)
- sys.modules[module] = mod
- return mod
+ return _LazyModule(module, spec, lock)
diff --git a/tests/utils/test_lazy_import.py b/tests/utils/test_lazy_import.py
index b65e6d83c..5c7936ea6 100644
--- a/tests/utils/test_lazy_import.py
+++ b/tests/utils/test_lazy_import.py
@@ -1,3 +1,4 @@
+import importlib
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
@@ -39,6 +40,31 @@ def test_require_returns_cached_module():
assert mod is sys.modules["json"]
+def test_require_initializes_package_before_importing_submodule(tmp_path, monkeypatch):
+ package_name = "dspy_lazy_submodule_package"
+ package = tmp_path / package_name
+ package.mkdir()
+ (package / "__init__.py").write_text("initialized = True\nfrom .models import Model\n")
+ (package / "models.py").write_text("from .constants import VALUE\nclass Model:\n value = VALUE\n")
+ (package / "constants.py").write_text("VALUE = 42\n")
+ monkeypatch.syspath_prepend(tmp_path)
+
+ try:
+ proxy = require(package_name)
+ assert "initialized" not in vars(proxy)
+ assert f"{package_name}.models" not in sys.modules
+
+ # Binding constants to the parent must not initialize it while models is still importing.
+ models = importlib.import_module(f"{package_name}.models")
+
+ assert proxy.initialized is True
+ assert proxy.Model is models.Model
+ assert models.Model.value == 42
+ finally:
+ for name in (package_name, f"{package_name}.models", f"{package_name}.constants"):
+ sys.modules.pop(name, None)
+
+
def test_require_is_safe_under_concurrent_first_use(tmp_path, monkeypatch):
module_name = "dspy_lazy_threaded_module"
counter_path = tmp_path / "imports.txt"