Core — Result Types¶
TaipanStack's core module provides Rust-inspired Result types for explicit, type-safe error handling.
taipanstack.core.result¶
Result type utilities for functional error handling.
Provides Rust-style Result types (Ok/Err) for explicit error handling, avoiding exceptions for expected failure cases. This promotes safer, more predictable code.
Example
from taipanstack.core.result import safe, Ok, Err @safe ... def divide(a: int, b: int) -> float: ... if b == 0: ... raise ValueError("division by zero") ... return a / b result = divide(10, 0) match result: ... case Err(e): ... print(f"Error: {e}") ... case Ok(value): ... print(f"Result: {value}") Error: division by zero
SafeFromDecorator
¶
Bases: Protocol[E_co]
Protocol for safe_from decorator.
safe
¶
safe(
func: Callable[P, T],
) -> Callable[P, Result[T, Exception]]
safe(
func: Callable[P, Coroutine[Any, Any, T]],
) -> Callable[
P, Coroutine[Any, Any, Result[T, Exception]]
]
safe(
func: Callable[P, T]
| Callable[P, Coroutine[Any, Any, T]],
) -> (
Callable[P, Result[T, Exception]]
| Callable[
P, Coroutine[Any, Any, Result[T, Exception]]
]
)
Wrap a sync or async function to convert exceptions into Err results.
Detect whether func is a coroutine function and choose the
appropriate wrapper so that await-able functions remain
await-able and synchronous functions stay synchronous.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
The sync or async function to wrap.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[P, Result[T, Exception]] | Callable[P, Coroutine[Any, Any, Result[T, Exception]]]
|
A wrapped function that returns |
Callable[P, Result[T, Exception]] | Callable[P, Coroutine[Any, Any, Result[T, Exception]]]
|
(or a coroutine resolving to one). |
Example
@safe ... def parse_int(s: str) -> int: ... return int(s) parse_int("42") Ok(42) parse_int("invalid") Err(ValueError("invalid literal for int()..."))
safe_from
¶
safe_from(
*exception_types: type[E],
) -> SafeFromDecorator[E]
Decorator factory to catch specific exceptions as Err.
Only catches specified exception types; others propagate normally.
| PARAMETER | DESCRIPTION |
|---|---|
*exception_types
|
Exception types to convert to Err.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SafeFromDecorator[E]
|
Decorator that wraps function with selective error handling. |
Example
@safe_from(ValueError, TypeError) ... def process(data: str) -> int: ... return int(data) process("abc") Err(ValueError(...))
collect_results
¶
collect_results(
results: Iterable[Result[T, E]],
) -> Result[list[T], E]
Collect an iterable of Results into a single Result.
If all results are Ok, returns Ok with list of values. If any result is Err, returns the first Err encountered.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
Iterable of Result objects.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[list[T], E]
|
Ok(list[T]) if all are Ok, otherwise first Err. |
Example
collect_results([Ok(1), Ok(2), Ok(3)]) Ok([1, 2, 3]) collect_results([Ok(1), Err("fail"), Ok(3)]) Err("fail")
map_async
async
¶
map_async(
result: Ok[T],
func: Callable[[T], Coroutine[Any, Any, U]],
) -> Result[U, E]
map_async(
result: Err[E],
func: Callable[[T], Coroutine[Any, Any, U]],
) -> Err[E]
map_async(
result: Result[T, E],
func: Callable[[T], Coroutine[Any, Any, U]],
) -> Result[U, E]
map_async(
result: Result[T, E],
func: Callable[[T], Coroutine[Any, Any, U]],
) -> Result[U, E]
Asynchronously apply a function to the value of an Ok result.
If the result is Err, returns it unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The Result to process.
TYPE:
|
func
|
Coroutine function to apply to the Ok value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[U, E]
|
New Result containing the processed value or original error. |
Example
async def process(x: int) -> str: ... return str(x * 2) await map_async(Ok(5), process) Ok('10') await map_async(Err("fail"), process) Err('fail')
and_then_async
async
¶
and_then_async(
result: Ok[T],
func: Callable[
[T], Coroutine[Any, Any, Result[U, E]]
],
) -> Result[U, E]
and_then_async(
result: Err[E],
func: Callable[
[T], Coroutine[Any, Any, Result[U, E]]
],
) -> Err[E]
and_then_async(
result: Result[T, E],
func: Callable[
[T], Coroutine[Any, Any, Result[U, E]]
],
) -> Result[U, E]
and_then_async(
result: Result[T, E],
func: Callable[
[T], Coroutine[Any, Any, Result[U, E]]
],
) -> Result[U, E]
Asynchronously chain operations that return Results.
If the result is Ok, asynchronously applies func and returns its Result.
If the result is Err, returns it unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The Result to process.
TYPE:
|
func
|
Coroutine function taking the Ok value and returning a new Result.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[U, E]
|
The new Result from |
Example
async def fetch_user(uid: int) -> Result[str, ValueError]: ... if uid == 1: ... return Ok("Alice") ... return Err(ValueError("User not found")) await and_then_async(Ok(1), fetch_user) Ok('Alice') await and_then_async(Ok(2), fetch_user) Err(ValueError('User not found')) await and_then_async(Err(ValueError("No DB")), fetch_user) Err(ValueError('No DB'))
Compat¶
Python Version Compatibility and Feature Detection.
This module provides runtime detection of Python version and available performance features, enabling version-specific optimizations while maintaining compatibility with Python 3.11+.
Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
PY311
module-attribute
¶
PY311: Final[bool] = PY_VERSION >= (3, 11)
True if running Python 3.11 or higher.
PY312
module-attribute
¶
PY312: Final[bool] = PY_VERSION >= (3, 12)
True if running Python 3.12 or higher.
PY313
module-attribute
¶
PY313: Final[bool] = PY_VERSION >= (3, 13)
True if running Python 3.13 or higher.
PY314
module-attribute
¶
PY314: Final[bool] = PY_VERSION >= (3, 14)
True if running Python 3.14 or higher.
ENV_ENABLE_EXPERIMENTAL
module-attribute
¶
ENV_ENABLE_EXPERIMENTAL = 'STACK_ENABLE_EXPERIMENTAL'
Environment variable to enable experimental features (JIT, free-threading).
ENV_OPTIMIZATION_LEVEL
module-attribute
¶
ENV_OPTIMIZATION_LEVEL = 'STACK_OPTIMIZATION_LEVEL'
Optimization level: 0=none, 1=safe, 2=aggressive (requires experimental).
VersionTier
¶
Bases: StrEnum
Python version tier for optimization profiles.
PythonFeatures
dataclass
¶
PythonFeatures(
version: tuple[int, int, int],
version_string: str,
tier: VersionTier,
has_jit: bool = False,
has_free_threading: bool = False,
has_mimalloc: bool = False,
has_tail_call_interpreter: bool = False,
has_exception_groups: bool = False,
has_self_type: bool = False,
has_type_params: bool = False,
has_fstring_improvements: bool = False,
has_override_decorator: bool = False,
has_deprecated_decorator: bool = False,
has_deferred_annotations: bool = False,
experimental_enabled: bool = False,
)
Available Python features based on version and build configuration.
This dataclass is immutable and optimized for performance with slots.
is_experimental_enabled
¶
is_experimental_enabled(
*, force_refresh: bool = False
) -> bool
Check if experimental features are explicitly enabled.
Features are cached after first detection for performance.
| PARAMETER | DESCRIPTION |
|---|---|
force_refresh
|
If True, re-detect instead of using cache.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if STACK_ENABLE_EXPERIMENTAL=1 is set. |
get_optimization_level
¶
get_optimization_level(
*, force_refresh: bool = False
) -> int
Get the configured optimization level.
Features are cached after first detection for performance.
| PARAMETER | DESCRIPTION |
|---|---|
force_refresh
|
If True, re-detect instead of using cache.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
0 = No optimizations |
int
|
1 = Safe optimizations only (default) |
int
|
2 = Aggressive optimizations (requires experimental) |
get_features
¶
get_features(
*, force_refresh: bool = False
) -> PythonFeatures
Detect and return available Python features.
Features are cached after first detection for performance.
| PARAMETER | DESCRIPTION |
|---|---|
force_refresh
|
If True, re-detect features instead of using cache.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PythonFeatures
|
PythonFeatures dataclass with all detected features. |
get_python_info
¶
get_python_info() -> dict[str, object]
Get comprehensive Python runtime information.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, object]
|
Dictionary with version, platform, and feature information. |
Optimizations¶
Python Version-Specific Optimization Profiles.
This module provides optimization strategies tailored to different Python versions, enabling performance improvements while maintaining stability.
Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
OptimizationProfile
dataclass
¶
OptimizationProfile(
gc_threshold_0: int = 700,
gc_threshold_1: int = 10,
gc_threshold_2: int = 10,
gc_freeze_enabled: bool = False,
thread_pool_multiplier: float = 1.0,
max_thread_pool_size: int = 32,
prefer_slots: bool = True,
use_frozen_dataclasses: bool = True,
prefer_match_statements: bool = False,
prefer_exception_groups: bool = False,
prefer_type_params: bool = False,
enable_perf_hints: bool = False,
aggressive_inlining: bool = False,
enable_experimental: bool = False,
)
Version-specific optimization settings.
This profile defines recommended settings based on Python version and available features. All settings follow the stability-first principle.
OptimizationResult
dataclass
¶
OptimizationResult(
success: bool,
applied: tuple[str, ...],
skipped: tuple[str, ...],
errors: tuple[str, ...],
)
Result of applying optimizations.
get_optimization_profile
¶
get_optimization_profile(
*, force_refresh: bool = False
) -> OptimizationProfile
Get the optimization profile for the current Python version.
| PARAMETER | DESCRIPTION |
|---|---|
force_refresh
|
If True, re-detect instead of using cache.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
OptimizationProfile
|
OptimizationProfile suitable for the runtime environment. |
apply_optimizations
¶
apply_optimizations(
*,
profile: OptimizationProfile | None = None,
apply_gc: bool = True,
freeze_after: bool = False,
force_refresh: bool = False,
) -> OptimizationResult
Apply runtime optimizations based on profile.
This function applies safe, reversible optimizations to the Python runtime. It is designed to be called once at application startup.
| PARAMETER | DESCRIPTION |
|---|---|
profile
|
Optimization profile to use (auto-detected if None).
TYPE:
|
apply_gc
|
Whether to apply GC tuning.
TYPE:
|
freeze_after
|
Whether to freeze objects after applying.
TYPE:
|
force_refresh
|
Whether to force re-detection of profile if none is provided.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
OptimizationResult
|
OptimizationResult with details of what was applied. |
get_recommended_thread_pool_size
¶
get_recommended_thread_pool_size(
*, force_refresh: bool = False
) -> int
Get recommended thread pool size based on version and features.
| PARAMETER | DESCRIPTION |
|---|---|
force_refresh
|
If True, re-detect instead of using cache.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Recommended number of threads for ThreadPoolExecutor. |
should_use_slots
¶
should_use_slots() -> bool
Check if slots should be used for new classes.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if slots are recommended for current version. |
should_use_frozen_dataclass
¶
should_use_frozen_dataclass() -> bool
Check if frozen=True should be used for dataclasses.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if frozen dataclasses are recommended. |