Coverage for src / vivarium_compat / _compat.py: 69%

52 statements  

« prev     ^ index     » next       coverage.py v7.14.0, created at 2026-05-18 19:31 +0000

1"""Backward-compatible import redirects for the vivarium monorepo migration. 

2 

3Intercepts old-style imports (e.g. ``import layered_config_tree``, 

4``from vivarium_public_health.disease import DiseaseModel``) and transparently 

5redirects them to the new ``vivarium.*`` namespace, emitting a DeprecationWarning. 

6 

7Activated at interpreter startup via ``vivarium_compat.pth`` so the hook is in 

8place before any user code runs. 

9 

10To add a redirect when a package migrates, add an entry to ``_REDIRECTS`` and 

11bump the ``vivarium-compat`` version in ``pyproject.toml``. Entries are safe 

12to add *before* the target package is released: if the new module isn't 

13importable, the hook falls back to letting the old on-disk package resolve 

14normally, so installations during the transition window aren't broken. 

15 

16Remove this module once all downstream packages have released versions that use 

17the new import paths and the deprecation period has ended. 

18""" 

19 

20import importlib 

21import importlib.abc 

22import importlib.machinery 

23import sys 

24import warnings 

25from types import ModuleType 

26 

27# Old import root -> new import root. 

28# Entries here are safe to populate ahead of the target package's release: 

29# if the new target isn't installed yet, the hook falls back to the old 

30# package's normal on-disk location (so existing installations during the 

31# transition window keep working). 

32_REDIRECTS: dict[str, str] = { 

33 # Renamed top-level packages 

34 "vivarium_profiling": "vivarium.profiling", 

35 "risk_distributions": "vivarium.risk_distributions", 

36 # FIXME [MIC-7113]: the layered_config_tree redirect is disabled until vivarium 

37 # is migrated and all `from layered_config_tree import ...` statements are updated. 

38 # "layered_config_tree": "vivarium.config_tree", 

39 # "vivarium_public_health": "vivarium.public_health", 

40 # "vivarium_cluster_tools": "vivarium.cluster_tools", 

41 # "vivarium_testing_utils": "vivarium.testing_utils", 

42 # "vivarium.examples": "vivarium.core.examples", 

43 # "vivarium.framework": "vivarium.core.framework", 

44 # "vivarium.interface": "vivarium.core.interface", 

45 # "vivarium.component": "vivarium.core.component", 

46 # "vivarium.exceptions": "vivarium.core.exceptions", 

47 # "vivarium.manager": "vivarium.core.manager", 

48 # "vivarium.testing_utilities": "vivarium.core.testing_utilities", 

49 # "vivarium.types": "vivarium.core.types", 

50 # "vivarium_helpers": "vivarium.helpers", 

51 # "gbd_mapping": "vivarium.gbd_mapping", 

52} 

53 

54# Tracks which old names are currently being resolved to prevent infinite 

55# recursion if a redirect target somehow re-triggers the same old-name import. 

56_resolving: set[str] = set() 

57 

58 

59def _match(fullname: str) -> tuple[str, str] | None: 

60 """Return (old_prefix, new_prefix) if fullname matches a redirect, else None. 

61 

62 Longer prefixes take precedence so more-specific entries win over broader ones. 

63 """ 

64 for old, new in sorted(_REDIRECTS.items(), key=lambda x: -len(x[0])): 

65 if fullname == old or fullname.startswith(old + "."): 

66 return old, new 

67 return None 

68 

69 

70class _CompatFinder(importlib.abc.MetaPathFinder): 

71 """Meta-path finder that redirects deprecated import paths to new locations.""" 

72 

73 def find_spec( 

74 self, 

75 fullname: str, 

76 path: object, 

77 target: ModuleType | None = None, 

78 ) -> importlib.machinery.ModuleSpec | None: 

79 match = _match(fullname) 

80 if match is None: 

81 return None 

82 

83 old_prefix, new_prefix = match 

84 new_name = new_prefix + fullname[len(old_prefix) :] 

85 

86 # Only warn on first import. After exec_module runs, sys.modules[fullname] 

87 # is set to the real module, so subsequent imports return it directly without 

88 # ever reaching find_spec again. This branch fires only in unusual re-entry 

89 # scenarios (e.g. reload()). 

90 if fullname not in sys.modules: 

91 # stacklevel=2 points into importlib internals rather than the caller's 

92 # import statement - the exact depth is CPython-version-dependent. 

93 # The warning message itself is the actionable part. 

94 warnings.warn( 

95 f"'{fullname}' has moved to '{new_name}'. " 

96 "Update your imports. This redirect will be removed in a future release.", 

97 DeprecationWarning, 

98 stacklevel=2, 

99 ) 

100 # submodule_search_locations is intentionally not set on the spec. CPython's 

101 # import machinery calls exec_module before checking __path__ on any child import, 

102 # and exec_module replaces sys.modules[fullname] with the real module (which already 

103 # has the correct __path__). Setting it to [] would be a no-op at best and misleading 

104 # at worst since we don't know at spec-creation time whether the target is a package. 

105 return importlib.machinery.ModuleSpec( 

106 fullname, _CompatLoader(fullname, new_name) 

107 ) 

108 

109 

110class _CompatLoader(importlib.abc.Loader): 

111 """Loads the real module at the new location and aliases it under the old name.""" 

112 

113 def __init__(self, old_name: str, new_name: str) -> None: 

114 self._old_name = old_name 

115 self._new_name = new_name 

116 

117 def exec_module(self, module: ModuleType) -> None: 

118 if self._old_name in _resolving: 

119 raise ImportError( 

120 f"Circular redirect detected: '{self._old_name}' -> '{self._new_name}'" 

121 ) 

122 _resolving.add(self._old_name) 

123 try: 

124 try: 

125 real = importlib.import_module(self._new_name) 

126 except ModuleNotFoundError: 

127 # FIXME: MIC-7100 Revert when all packages are migrated 

128 # New target isn't installed. Fall back to the old name's actual 

129 # on-disk location so installations during the transition window 

130 # — old package still installed, new package not yet released — 

131 # keep working. The DeprecationWarning was already emitted in 

132 # find_spec(); users will see it whether or not the fallback fires. 

133 real = _import_bypassing_compat(self._old_name) 

134 # Register under the old name so subsequent imports hit sys.modules directly. 

135 sys.modules[self._old_name] = real 

136 # Defensive: covers the case where another import hook holds a direct 

137 # reference to the placeholder module object rather than re-reading sys.modules. 

138 module.__dict__.update(real.__dict__) 

139 # __spec__.name will show the new name (e.g. "vivarium.config_tree"), not the 

140 # old one. This is intentional: sys.modules[old_name] IS real, so its metadata 

141 # correctly describes its actual location. Users inspecting __spec__ after 

142 # migrating their imports will see the right thing. 

143 module.__spec__ = real.__spec__ 

144 finally: 

145 _resolving.discard(self._old_name) 

146 

147 

148def _import_bypassing_compat(name: str) -> ModuleType: 

149 """Import `name` without going through our compat finder. 

150 

151 Used to fall back to a name's real on-disk location when the redirect target 

152 isn't installed. Temporarily removes our finder from sys.meta_path so the 

153 standard PathFinder resolves the name directly. Also clears any placeholder 

154 sys.modules entry the import system set when our find_spec returned a spec. 

155 """ 

156 sys.modules.pop(name, None) 

157 saved: list[tuple[int, _CompatFinder]] = [ 

158 (i, f) for i, f in enumerate(sys.meta_path) if isinstance(f, _CompatFinder) 

159 ] 

160 for _, f in saved: 

161 sys.meta_path.remove(f) 

162 try: 

163 return importlib.import_module(name) 

164 finally: 

165 # Reinsert in original order so any other meta_path entries stay in place. 

166 for i, f in saved: 

167 sys.meta_path.insert(i, f) 

168 

169 

170def install_compat_finder() -> None: 

171 """Install the compat finder into sys.meta_path (idempotent).""" 

172 if not any(isinstance(f, _CompatFinder) for f in sys.meta_path): 

173 sys.meta_path.insert(0, _CompatFinder())