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
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Python Version Compatibility and Feature Detection.
4This module provides runtime detection of Python version and available
5performance features, enabling version-specific optimizations while
6maintaining compatibility with Python 3.11+.
8Following TaipanStack pillars: Security, Stability, Simplicity,
9Scalability, Compatibility.
10"""
12import logging
13import os
14import platform
15import sys
16import sysconfig
17from dataclasses import dataclass
18from enum import StrEnum
19from typing import Final
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]
35logger = logging.getLogger(__name__)
37# =============================================================================
38# Version Constants
39# =============================================================================
41PY_VERSION: Final = sys.version_info
42"""Current Python version tuple."""
44PY311: Final[bool] = PY_VERSION >= (3, 11)
45"""True if running Python 3.11 or higher."""
47PY312: Final[bool] = PY_VERSION >= (3, 12)
48"""True if running Python 3.12 or higher."""
50PY313: Final[bool] = PY_VERSION >= (3, 13)
51"""True if running Python 3.13 or higher."""
53PY314: Final[bool] = PY_VERSION >= (3, 14)
54"""True if running Python 3.14 or higher."""
56PY315: Final[bool] = PY_VERSION >= (3, 15)
57"""True if running Python 3.15 or higher."""
60class VersionTier(StrEnum):
61 """Python version tier for optimization profiles."""
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
69# =============================================================================
70# Environment Variables for Experimental Features
71# =============================================================================
73ENV_ENABLE_EXPERIMENTAL = "STACK_ENABLE_EXPERIMENTAL"
74"""Environment variable to enable experimental features (JIT, free-threading)."""
76ENV_OPTIMIZATION_LEVEL = "STACK_OPTIMIZATION_LEVEL"
77"""Optimization level: 0=none, 1=safe, 2=aggressive (requires experimental)."""
80# =============================================================================
81# Feature Detection Functions
82# =============================================================================
85def _check_jit_available() -> bool:
86 """Check if JIT compiler is available and enabled.
88 JIT is available in Python 3.13+ when built with --enable-experimental-jit.
89 """
90 if not PY313:
91 return False
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
101def _check_nogil_flag() -> bool | None:
102 """Check if nogil flag is present and enabled.
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.
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
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]
128def _check_free_threading_available() -> bool:
129 """Check if free-threading (no-GIL) build is being used.
131 Free-threading is available in Python 3.13+ experimental builds.
132 """
133 if not PY313:
134 return False
136 nogil = _check_nogil_flag()
137 if nogil is not None:
138 return nogil
140 return _check_disable_gil_config()
143def _check_mimalloc_available() -> bool:
144 """Check if mimalloc allocator is being used.
146 mimalloc is the default allocator in Python 3.13+ on some platforms.
147 """
148 if not PY313:
149 return False
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
159def _check_tail_call_interpreter() -> bool:
160 """Check if tail-call interpreter optimization is available.
162 Tail-call interpreter is available in Python 3.14+.
163 """
164 return PY314
167_cached_experimental_enabled: bool | None = None
170def is_experimental_enabled(*, force_refresh: bool = False) -> bool:
171 """Check if experimental features are explicitly enabled.
173 Features are cached after first detection for performance.
175 Args:
176 force_refresh: If True, re-detect instead of using cache.
178 Returns:
179 True if STACK_ENABLE_EXPERIMENTAL=1 is set.
181 """
182 global _cached_experimental_enabled # noqa: PLW0603
184 if _cached_experimental_enabled is not None and not force_refresh:
185 return _cached_experimental_enabled
187 value = os.environ.get(ENV_ENABLE_EXPERIMENTAL, "").lower()
188 _cached_experimental_enabled = value in {"1", "true", "yes", "on"}
189 return _cached_experimental_enabled
192_cached_optimization_level: int | None = None
195def get_optimization_level(*, force_refresh: bool = False) -> int:
196 """Get the configured optimization level.
198 Features are cached after first detection for performance.
200 Args:
201 force_refresh: If True, re-detect instead of using cache.
203 Returns:
204 0 = No optimizations
205 1 = Safe optimizations only (default)
206 2 = Aggressive optimizations (requires experimental)
208 """
209 global _cached_optimization_level # noqa: PLW0603
211 if _cached_optimization_level is not None and not force_refresh:
212 return _cached_optimization_level
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
220 return _cached_optimization_level
223# =============================================================================
224# Feature Data Classes
225# =============================================================================
228@dataclass(frozen=True, slots=True)
229class PythonFeatures:
230 """Available Python features based on version and build configuration.
232 This dataclass is immutable and optimized for performance with slots.
233 """
235 version: tuple[int, int, int]
236 version_string: str
237 tier: VersionTier
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
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+
253 # Experimental features enabled
254 experimental_enabled: bool = False
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 }
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
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 }
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 }
314# =============================================================================
315# Main Detection Functions
316# =============================================================================
318# Cache the features after first detection
319_cached_features: PythonFeatures | None = None
322def get_features(*, force_refresh: bool = False) -> PythonFeatures:
323 """Detect and return available Python features.
325 Features are cached after first detection for performance.
327 Args:
328 force_refresh: If True, re-detect features instead of using cache.
330 Returns:
331 PythonFeatures dataclass with all detected features.
333 """
334 global _cached_features # noqa: PLW0603 - intentional cache pattern
336 if _cached_features is not None and not force_refresh:
337 return _cached_features
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()
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 )
353 _cached_features = features
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 )
364 return features
367def get_python_info() -> dict[str, object]:
368 """Get comprehensive Python runtime information.
370 Returns:
371 Dictionary with version, platform, and feature information.
373 """
374 features = get_features()
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 }