weekly icon indicating copy to clipboard operation
weekly copied to clipboard

【开源自荐】utype - 基于 Python 类型注解的数据解析与类型安全保障库

Open voidZXL opened this issue 2 years ago • 1 comments

  • 项目地址:https://github.com/utilmeta/utype

    • 官网:https://utype.io/
    • 中文文档:https://utype.io/zh/
  • 类别:Python

  • 项目标题:utype - 基于 Python 类型注解的数据解析与类型安全保障库

  • 项目描述: utype 是一个基于 Python 类型注解的数据类型声明与解析库,能够在运行时根据你的声明对类与函数的参数进行解析转化,保障项目的类型安全

  • 亮点: 相比于pydantic 等库,支持了对函数参数类型声明的解析(包括生成器与异步函数),支持简洁的约束和类型声明,支持多种逻辑条件组合类型,支持丰富的解析选项与偏好配置

  • 示例代码:

import utype

@utype.parse
def login(
    username: str = utype.Param(regex='[0-9a-zA-Z]{3,20}'),
    password: str = utype.Param(min_length=6)
):
    # 你可以直接开始编写逻辑了
    return username, password

print(login('alice', 123456))
('alice', '123456')

try:
    login('@invalid', 123456)
except utype.exc.ParseError as e:
    print(e)
    """
    parse item: ['username'] failed: 
    Constraint: <regex>: '[0-9a-zA-Z]{3,20}' violated
    """
from utype import Schema, Field, exc
from datetime import datetime

class UserSchema(Schema):
    username: str = Field(regex='[0-9a-zA-Z]{3,20}')
    signup_time: datetime

# 1. 正常输入
data = {'username': 'bob', 'signup_time': '2022-10-11 10:11:12'}
print(UserSchema(**data))
#> UserSchema(username='bob', signup_time=datetime.datetime(2022, 10, 11, 10, 11, 12))

# 2. 异常输入
try:
    UserSchema(username='@invalid', signup_time='2022-10-11 10:11:12')
except exc.ParseError as e:
    print(e)
    """
    parse item: ['username'] failed: 
    Constraint: <regex>: '[0-9a-zA-Z]{3,20}' violated
    """
  • 后续更新计划:
    • 支持生成 json-schema 格式的输入输出模板文档
    • 完善解析错误的处理机制,包括错误处理钩子函数等
    • 支持环境变量和配置文件的解析和管理
    • 支持命令行参数的声明与解析
    • 支持 Python 泛型,类型变量等更多类型注解语法
    • 开发 Pycharm / VS Code 插件,支持对约束,逻辑类型和嵌套类型的 IDE 检测与提示

voidZXL avatar Feb 13 '23 13:02 voidZXL

挺有趣的,其实一直奇怪py官方为什么不提供类似的功能, 参数声明类型就是摆设

xlight avatar Feb 15 '23 00:02 xlight