Skip to content

[开源推荐] typeric: python中的实用类,如Result和Option等 #2961

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
newdee opened this issue May 25, 2025 · 0 comments
Open

[开源推荐] typeric: python中的实用类,如Result和Option等 #2961

newdee opened this issue May 25, 2025 · 0 comments
Assignees

Comments

@newdee
Copy link

newdee commented May 25, 2025

项目地址

https://github.com/newdee/typeric

类别

Python

项目标题

Python实用类,如rust风格的Result和Option等

项目描述

typeric 是一个面向 Python 的实用类型工具包,专注于清晰性、安全性和易用性。它最初是为了提升我个人的开发体验而构建的,但我也希望它能对他人有所帮助。

目前,typeric 提供了轻量且支持模式匹配的类型,比如 Result 和 Option —— 设计灵感来自 Rust。未来还计划引入更多常见的类型模式和错误处理抽象。

亮点

  • ✅ 函数式风格的 Result 类型:Ok(value)Err(error)
  • 🌀 轻量级 Option 类型:Some(value)NONE
  • 🧩 支持模式匹配(通过 __match_args__
  • 🔒 不可变设计,提供 .map() / .map_err() / .unwrap() / .unwrap_or() 等辅助方法
  • 🔧 简洁的类型签名:Result[T, E]Option[T]
  • 🛠️ 易于扩展 —— 更多类型工具即将推出

示例代码

### `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")

截图或演示视频

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants