< 返回版块

dfine 发表于 2025-05-25 10:54

Tags:Types, Result, Option

鉴于Rust中优秀的Result和Option枚举,提供了python中的类似实现。后续会添加更多实用类。详情如下:

📦 typeric

typeric is a practical type utility toolkit for Python, focused on clarity, safety, and ergonomics. It was originally built to make my own development experience smoother, but I hope it proves useful to others as well.
It currently provides lightweight, pattern-matchable types like Result and Option — inspired by Rust — with plans to include more common type patterns and error-handling abstractions.

pip install typeric

🚀 Features

  • ✅ Functional-style Result type: Ok(value) and Err(error)
  • 🌀 Lightweight Option type: Some(value) and NONE
  • 🧩 Pattern matching support (__match_args__)
  • 🔒 Immutable with .map() / .map_err() / .unwrap() / .unwrap_or() helpers
  • 🔧 Clean type signatures: Result[T, E] and Option[T]
  • 🛠️ Built for extensibility — more type tools coming

🔍 Quick Example

Result

from typeric.result import Result, Ok, Err

def parse_number(text: str) -> Result[int, str]:
    try:
        return Ok(int(text))
    except ValueError:
        return Err("Not a number")

match parse_number("42"):
    case Ok(value):
        print("Parsed:", value)
    case Err(error):
        print("Failed:", error)

Option

from typeric.option import Option, Some, NONE

def maybe_get(index: int, items: list[str]) -> Option[str]:
    if 0 <= index < len(items):
        return Some(items[index])
    return NONE

match maybe_get(1, ["a", "b", "c"]):
    case Some(value):
        print("Got:", value)
    case NONE:
        print("Nothing found")

def func_a(x: int) -> Result[int, str]:
    if x < 0:
        return Err("negative input")
    return Ok(x * 2)


@spreadable
def func_b(y: int) -> Result[int, str]:
    a = func_a(y).spread()
    return Ok(a + 1)


def test_func_b_success():
    assert func_b(5) == Ok(11)  # 5*2=10 +1=11


def test_func_b_propagate_error():
    assert func_b(-2) == Err("negative input")

Repo

评论区

写评论
作者 dfine 2025-05-26 22:28

这边主要是提供一套实用的工具类,刚开始只是实现了核心的两个类型。

如果 Python 原生就支持类似的错误传播机制,那确实不需要这么复杂。

这里的设计灵感来自 Rust,但我并不是想强行把 Python 当 Rust 用, 而是借鉴 Rust 中优秀的枚举设计和 trait 实现思想, 结合 Python 语言特点,实现一套规范且实用的工具。

Rust 的精妙不仅在于链式调用,更重要的是它的结构设计和思维方式, 每种语言都有自己的最佳实践和用法。

这个工具类的意义,就是帮助 Python 项目也能有一套类似于 Rust 风格的错误处理和结果传播机制。

--
👇
lxl66566: 没啥意义。 当前项目进度就只有 Option 和 Result,这些 python 原生类型系统都能实现,用起来也不算复杂。 Rust 这套的精髓是 monad 各种转换、链式调用和交互,但是 python lambda 太弱了,做不起来。

lxl66566 2025-05-26 21:08

没啥意义。 当前项目进度就只有 Option 和 Result,这些 python 原生类型系统都能实现,用起来也不算复杂。 Rust 这套的精髓是 monad 各种转换、链式调用和交互,但是 python lambda 太弱了,做不起来。

1 共 2 条评论, 1 页