Python Rusty Result Library: 在Python中使用Rust风格的Result类型
Project description
pyrsult: Rust 风格的 Result 类型在 Python 中的实现
PyRsult 是 Rust 风格的 Result 类型在 Python 中的实现。
注意: 是 PyRsult 而不是 PyResult 哦,Rs 是 Rust 的意思
pyrsult 是一个超轻量级的 Python 库,提供了类似于 Rust 语言中的Result<T, E>类型。它允许你以更优雅的方式处理可能失败的操作,避免使用异常来控制程序流程,使代码更加健壮和可读。
特性
- 🦀 Rust 风格的 Result 类型实现
- 🛡️ 类型安全的错误处理
- 🧩 简洁的 API 设计
- 📦 零依赖,纯 Python 实现
- 🧩 支持泛型类型提示
安装
pip install pyrsult
或者直接将result.py文件复制到你的项目中。
快速开始
from pyrsult import Result
def divide(a: float, b: float) -> Result[float, str]:
return Result.Success(a / b) if b != 0 else Result.Failure("Division by zero")
# 成功情况
result = divide(10, 2)
print(result) # Ok(5.0)
print(result.unwrap()) # 5.0
# 失败情况
result = divide(10, 0)
print(result) # Err('Division by zero')
print(result.unwrap_or(-1)) # -1
核心概念
pyrsult 提供了两种结果类型:
Success(T): 表示操作成功,包含一个成功值Failure(E): 表示操作失败,包含一个错误值
API 文档
工厂方法
| 方法 | 描述 |
|---|---|
Result.Success(value) |
创建一个成功结果 |
Result.Failure(error) |
创建一个失败结果 |
判别方法
| 方法 | 返回类型 | 描述 |
|---|---|---|
is_ok() |
bool |
是否为成功结果 |
is_err() |
bool |
是否为失败结果 |
取值方法
| 方法 | 返回类型 | 描述 |
|---|---|---|
unwrap() |
T |
获取成功值,失败时抛出异常 |
unwrap_err() |
E |
获取错误值,成功时抛出异常 |
unwrap_or(default) |
T |
获取成功值或默认值 |
unwrap_or_else(func) |
T |
获取成功值或调用函数处理错误 |
expect(msg) |
T |
类似 unwrap,但可自定义错误消息 |
示例用法
# 创建结果
success = Result.Success(42)
failure = Result.Failure("Error occurred")
# 检查结果类型
print(success.is_ok()) # True
print(failure.is_err()) # True
# 安全取值
print(success.unwrap()) # 42
print(failure.unwrap_or(0)) # 0
print(failure.unwrap_or_else(lambda e: len(e))) # 14
# 带错误消息的取值
try:
failure.expect("Operation failed")
except ValueError as e:
print(e) # Operation failed
实际应用示例
文件操作
def read_file(path: str) -> Result[str, str]:
try:
with open(path, 'r') as f:
return Result.Success(f.read())
except IOError as e:
return Result.Failure(str(e))
result = read_file("data.txt")
if result.is_ok():
print("File content:", result.unwrap())
else:
print("Error:", result.unwrap_err())
数据验证
def validate_age(age: int) -> Result[int, str]:
if age < 0:
return Result.Failure("Age cannot be negative")
if age > 120:
return Result.Failure("Age seems unrealistic")
return Result.Success(age)
user_age = validate_age(25)
match user_age:
case Result.Success(value):
print(f"Valid age: {value}")
case Result.Failure(error):
print(f"Invalid age: {error}")
链式操作
def process_data(data: str) -> Result[int, str]:
# 模拟可能失败的操作链
cleaned = Result.Success(data.strip())
if not cleaned.unwrap():
return Result.Failure("Empty data")
try:
number = int(cleaned.unwrap())
return Result.Success(number * 2)
except ValueError:
return Result.Failure("Not a number")
result = process_data(" 42 ")
print(result.unwrap_or(0)) # 84
设计理念
pyrsult 的设计遵循以下原则:
- 显式错误处理:强制开发者显式处理错误情况
- 类型安全:通过泛型提供编译时类型检查
- 不可变性:Result 对象一旦创建不可修改
- 最小化 API:只提供核心方法,保持简洁
- Pythonic 风格:遵循 Python 的命名和设计惯例
最佳实践
- 避免直接使用
unwrap():除非你确定结果一定是成功的 - 优先使用
unwrap_or和unwrap_or_else:提供默认值或错误处理逻辑 - 使用
expect提供有意义的错误信息:在调试和关键操作中 - 保持错误类型简单:通常使用字符串或简单对象作为错误类型
- 在 API 边界使用 Result:特别是在模块和包的公共接口
常见问题
Q: 是否支持链式操作? A: 当前版本不直接支持 map/and_then,但可以通过组合实现:
def map_result(result: Result[T, E], func) -> Result[Any, E]:
return Result.Success(func(result.unwrap())) if result.is_ok() else result
贡献指南
欢迎贡献代码!请遵循以下步骤:
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启 Pull Request
许可证
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
更新日志
v0.1.1 (2023-10-18)
- 完整的 API 文档
v0.1.0 (2023-10-18)
- 初始版本发布
- 实现核心 Result 类型
- 添加 Success 和 Failure 类
pyrsult - 让 Python 的错误处理更加优雅和可靠!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyrsult-0.1.0.tar.gz.
File metadata
- Download URL: pyrsult-0.1.0.tar.gz
- Upload date:
- Size: 5.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dfe9fd9eb1b73ad69009bf6cb1a1cfd6e9b3bf5e18c487408a1d5ee42b27ceeb
|
|
| MD5 |
769ba581cb30feaecf3c023ebbe39e49
|
|
| BLAKE2b-256 |
48f770bcbcf33a6967521a17a1e61ed8d900e7091bbdb39911ad63474e412822
|
Provenance
The following attestation bundles were made for pyrsult-0.1.0.tar.gz:
Publisher:
python-publish.yml on fexcode/pyrsult
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyrsult-0.1.0.tar.gz -
Subject digest:
dfe9fd9eb1b73ad69009bf6cb1a1cfd6e9b3bf5e18c487408a1d5ee42b27ceeb - Sigstore transparency entry: 621347964
- Sigstore integration time:
-
Permalink:
fexcode/pyrsult@27ad76b983d169754e28fc276002812a0f4324f6 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/fexcode
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@27ad76b983d169754e28fc276002812a0f4324f6 -
Trigger Event:
release
-
Statement type:
File details
Details for the file pyrsult-0.1.0-py3-none-any.whl.
File metadata
- Download URL: pyrsult-0.1.0-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c345a36afa54d2bb91bd0a2e8f47849c343dd37a2a7de23c54fe6200ab4cc866
|
|
| MD5 |
4d1b582bbc80f205af0683d31238fdbb
|
|
| BLAKE2b-256 |
19582cd17b61d849f90c45397d7b52701438ceda26dbee8337d576310baa610b
|
Provenance
The following attestation bundles were made for pyrsult-0.1.0-py3-none-any.whl:
Publisher:
python-publish.yml on fexcode/pyrsult
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyrsult-0.1.0-py3-none-any.whl -
Subject digest:
c345a36afa54d2bb91bd0a2e8f47849c343dd37a2a7de23c54fe6200ab4cc866 - Sigstore transparency entry: 621347965
- Sigstore integration time:
-
Permalink:
fexcode/pyrsult@27ad76b983d169754e28fc276002812a0f4324f6 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/fexcode
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@27ad76b983d169754e28fc276002812a0f4324f6 -
Trigger Event:
release
-
Statement type: