Coverage for src/taipanstack/core/compat.py: 100%

130 statements  

« prev     ^ index     » next       coverage.py v7.15.1, created at 2026-11-23 17:43 +0000

1""" 

2Python Version Compatibility and Feature Detection. 

3 

4This module provides runtime detection of Python version and available 

5performance features, enabling version-specific optimizations while 

6maintaining compatibility with Python 3.11+. 

7 

8Following TaipanStack pillars: Security, Stability, Simplicity, 

9Scalability, Compatibility. 

10""" 

11 

12import logging 

13import os 

14import platform 

15import sys 

16import sysconfig 

17from dataclasses import dataclass 

18from enum import StrEnum 

19from typing import Final 

20 

21__all__ = [ 

22 "PY311", 

23 "PY312", 

24 "PY313", 

25 "PY314", 

26 "PY315", 

27 "PY_VERSION", 

28 "PythonFeatures", 

29 "VersionTier", 

30 "get_features", 

31 "get_python_info", 

32 "is_experimental_enabled", 

33] 

34 

35logger = logging.getLogger(__name__) 

36 

37# ============================================================================= 

38# Version Constants 

39# ============================================================================= 

40 

41PY_VERSION: Final = sys.version_info 

42"""Current Python version tuple.""" 

43 

44PY311: Final[bool] = PY_VERSION >= (3, 11) 

45"""True if running Python 3.11 or higher.""" 

46 

47PY312: Final[bool] = PY_VERSION >= (3, 12) 

48"""True if running Python 3.12 or higher.""" 

49 

50PY313: Final[bool] = PY_VERSION >= (3, 13) 

51"""True if running Python 3.13 or higher.""" 

52 

53PY314: Final[bool] = PY_VERSION >= (3, 14) 

54"""True if running Python 3.14 or higher.""" 

55 

56PY315: Final[bool] = PY_VERSION >= (3, 15) 

57"""True if running Python 3.15 or higher.""" 

58 

59 

60class VersionTier(StrEnum): 

61 """Python version tier for optimization profiles.""" 

62 

63 STABLE = "stable" # 3.11 - fully stable, conservative optimizations 

64 ENHANCED = "enhanced" # 3.12 - improved features, moderate optimizations 

65 MODERN = "modern" # 3.13 - JIT/free-threading available (experimental) 

66 CUTTING_EDGE = "cutting_edge" # 3.14+ - latest optimizations 

67 

68 

69# ============================================================================= 

70# Environment Variables for Experimental Features 

71# ============================================================================= 

72 

73ENV_ENABLE_EXPERIMENTAL = "STACK_ENABLE_EXPERIMENTAL" 

74"""Environment variable to enable experimental features (JIT, free-threading).""" 

75 

76ENV_OPTIMIZATION_LEVEL = "STACK_OPTIMIZATION_LEVEL" 

77"""Optimization level: 0=none, 1=safe, 2=aggressive (requires experimental).""" 

78 

79 

80# ============================================================================= 

81# Feature Detection Functions 

82# ============================================================================= 

83 

84 

85def _check_jit_available() -> bool: 

86 """Check if JIT compiler is available and enabled. 

87 

88 JIT is available in Python 3.13+ when built with --enable-experimental-jit. 

89 """ 

90 if not PY313: 

91 return False 

92 

93 try: 

94 # Check if the JIT module exists (Python 3.13+) 

95 # This is a build-time option, not all builds have it 

96 return hasattr(sys, "_jit") or "jit" in sys.flags.__class__.__annotations__ 

97 except (AttributeError, TypeError): 

98 return False 

99 

100 

101def _check_nogil_flag() -> bool | None: 

102 """Check if nogil flag is present and enabled. 

103 

104 Returns: 

105 True if the flag is present and True. 

106 False if the flag is present and False. 

107 None if the flag is not present. 

108 

109 """ 

110 try: 

111 if hasattr(sys.flags, "nogil"): 

112 return bool(sys.flags.nogil) # type: ignore[misc] 

113 except (AttributeError, TypeError): 

114 _ = None 

115 return None 

116 

117 

118def _check_disable_gil_config() -> bool: 

119 """Check if build was configured with --disable-gil.""" 

120 try: 

121 config_args = sysconfig.get_config_var("CONFIG_ARGS") or "" # type: ignore[misc] 

122 except (AttributeError, TypeError): 

123 return False 

124 else: 

125 return "--disable-gil" in config_args # type: ignore[misc] 

126 

127 

128def _check_free_threading_available() -> bool: 

129 """Check if free-threading (no-GIL) build is being used. 

130 

131 Free-threading is available in Python 3.13+ experimental builds. 

132 """ 

133 if not PY313: 

134 return False 

135 

136 nogil = _check_nogil_flag() 

137 if nogil is not None: 

138 return nogil 

139 

140 return _check_disable_gil_config() 

141 

142 

143def _check_mimalloc_available() -> bool: 

144 """Check if mimalloc allocator is being used. 

145 

146 mimalloc is the default allocator in Python 3.13+ on some platforms. 

147 """ 

148 if not PY313: 

149 return False 

150 

151 try: 

152 # Check if built with mimalloc 

153 config_args = sysconfig.get_config_var("CONFIG_ARGS") or "" # type: ignore[misc] 

154 return "mimalloc" in config_args.lower() # type: ignore[misc] 

155 except (AttributeError, TypeError): 

156 return False 

157 

158 

159def _check_tail_call_interpreter() -> bool: 

160 """Check if tail-call interpreter optimization is available. 

161 

162 Tail-call interpreter is available in Python 3.14+. 

163 """ 

164 return PY314 

165 

166 

167_cached_experimental_enabled: bool | None = None 

168 

169 

170def is_experimental_enabled(*, force_refresh: bool = False) -> bool: 

171 """Check if experimental features are explicitly enabled. 

172 

173 Features are cached after first detection for performance. 

174 

175 Args: 

176 force_refresh: If True, re-detect instead of using cache. 

177 

178 Returns: 

179 True if STACK_ENABLE_EXPERIMENTAL=1 is set. 

180 

181 """ 

182 global _cached_experimental_enabled # noqa: PLW0603 

183 

184 if _cached_experimental_enabled is not None and not force_refresh: 

185 return _cached_experimental_enabled 

186 

187 value = os.environ.get(ENV_ENABLE_EXPERIMENTAL, "").lower() 

188 _cached_experimental_enabled = value in {"1", "true", "yes", "on"} 

189 return _cached_experimental_enabled 

190 

191 

192_cached_optimization_level: int | None = None 

193 

194 

195def get_optimization_level(*, force_refresh: bool = False) -> int: 

196 """Get the configured optimization level. 

197 

198 Features are cached after first detection for performance. 

199 

200 Args: 

201 force_refresh: If True, re-detect instead of using cache. 

202 

203 Returns: 

204 0 = No optimizations 

205 1 = Safe optimizations only (default) 

206 2 = Aggressive optimizations (requires experimental) 

207 

208 """ 

209 global _cached_optimization_level # noqa: PLW0603 

210 

211 if _cached_optimization_level is not None and not force_refresh: 

212 return _cached_optimization_level 

213 

214 try: 

215 level = int(os.environ.get(ENV_OPTIMIZATION_LEVEL, "1")) 

216 _cached_optimization_level = max(0, min(2, level)) # Clamp to 0-2 

217 except ValueError: 

218 _cached_optimization_level = 1 

219 

220 return _cached_optimization_level 

221 

222 

223# ============================================================================= 

224# Feature Data Classes 

225# ============================================================================= 

226 

227 

228@dataclass(frozen=True, slots=True) 

229class PythonFeatures: 

230 """Available Python features based on version and build configuration. 

231 

232 This dataclass is immutable and optimized for performance with slots. 

233 """ 

234 

235 version: tuple[int, int, int] 

236 version_string: str 

237 tier: VersionTier 

238 

239 # Build features 

240 has_jit: bool = False 

241 has_free_threading: bool = False 

242 has_mimalloc: bool = False 

243 has_tail_call_interpreter: bool = False 

244 

245 # Language features by version 

246 has_exception_groups: bool = False # 3.11+ 

247 has_self_type: bool = False # 3.11+ 

248 has_type_params: bool = False # 3.12+ 

249 has_override_decorator: bool = False # 3.12+ 

250 has_deprecated_decorator: bool = False # 3.13+ 

251 has_deferred_annotations: bool = False # 3.14+ 

252 

253 # Experimental features enabled 

254 experimental_enabled: bool = False 

255 

256 def to_dict(self) -> dict[str, object]: 

257 """Convert to dictionary for serialization.""" 

258 return { 

259 "version": ".".join(map(str, self.version)), 

260 "tier": self.tier.value, 

261 "features": { 

262 "jit": self.has_jit, 

263 "free_threading": self.has_free_threading, 

264 "mimalloc": self.has_mimalloc, 

265 "tail_call_interpreter": self.has_tail_call_interpreter, 

266 }, 

267 "language": { 

268 "exception_groups": self.has_exception_groups, 

269 "self_type": self.has_self_type, 

270 "type_params": self.has_type_params, 

271 "override_decorator": self.has_override_decorator, 

272 "deprecated_decorator": self.has_deprecated_decorator, 

273 "deferred_annotations": self.has_deferred_annotations, 

274 }, 

275 "experimental_enabled": self.experimental_enabled, 

276 } 

277 

278 

279def _get_version_tier() -> VersionTier: 

280 """Determine the version tier based on Python version.""" 

281 if PY314: 

282 return VersionTier.CUTTING_EDGE 

283 if PY313: 

284 return VersionTier.MODERN 

285 if PY312: 

286 return VersionTier.ENHANCED 

287 return VersionTier.STABLE 

288 

289 

290def _get_build_features(experimental: bool) -> dict[str, bool]: 

291 """Determine build features based on experimental flag.""" 

292 return { 

293 "has_jit": _check_jit_available() if experimental else False, 

294 "has_free_threading": _check_free_threading_available() 

295 if experimental 

296 else False, 

297 "has_mimalloc": _check_mimalloc_available(), 

298 "has_tail_call_interpreter": _check_tail_call_interpreter(), 

299 } 

300 

301 

302def _get_language_features() -> dict[str, bool]: 

303 """Determine language features based on Python version.""" 

304 return { 

305 "has_exception_groups": PY311, 

306 "has_self_type": PY311, 

307 "has_type_params": PY312, 

308 "has_override_decorator": PY312, 

309 "has_deprecated_decorator": PY313, 

310 "has_deferred_annotations": PY314, 

311 } 

312 

313 

314# ============================================================================= 

315# Main Detection Functions 

316# ============================================================================= 

317 

318# Cache the features after first detection 

319_cached_features: PythonFeatures | None = None 

320 

321 

322def get_features(*, force_refresh: bool = False) -> PythonFeatures: 

323 """Detect and return available Python features. 

324 

325 Features are cached after first detection for performance. 

326 

327 Args: 

328 force_refresh: If True, re-detect features instead of using cache. 

329 

330 Returns: 

331 PythonFeatures dataclass with all detected features. 

332 

333 """ 

334 global _cached_features # noqa: PLW0603 - intentional cache pattern 

335 

336 if _cached_features is not None and not force_refresh: 

337 return _cached_features 

338 

339 tier = _get_version_tier() 

340 experimental = is_experimental_enabled(force_refresh=force_refresh) 

341 build_feats = _get_build_features(experimental) 

342 lang_feats = _get_language_features() 

343 

344 features = PythonFeatures( 

345 version=(PY_VERSION.major, PY_VERSION.minor, PY_VERSION.micro), 

346 version_string=f"{PY_VERSION.major}.{PY_VERSION.minor}.{PY_VERSION.micro}", 

347 tier=tier, 

348 **build_feats, 

349 **lang_feats, 

350 experimental_enabled=experimental, 

351 ) 

352 

353 _cached_features = features 

354 

355 # Log detected features at DEBUG level 

356 logger.debug( 

357 "Python %s detected (tier=%s, experimental=%s): %r", 

358 features.version_string, 

359 tier.value, 

360 experimental, 

361 features, 

362 ) 

363 

364 return features 

365 

366 

367def get_python_info() -> dict[str, object]: 

368 """Get comprehensive Python runtime information. 

369 

370 Returns: 

371 Dictionary with version, platform, and feature information. 

372 

373 """ 

374 features = get_features() 

375 

376 return { 

377 "version": features.version_string, 

378 "version_tuple": features.version, 

379 "tier": features.tier.value, 

380 "implementation": platform.python_implementation(), 

381 "platform": platform.platform(), 

382 "compiler": platform.python_compiler(), 

383 "features": features.to_dict(), 

384 "optimization_level": get_optimization_level(), 

385 }