当前位置: 代码网 > it编程>前端脚本>Python > Python的TypedDict基本用法

Python的TypedDict基本用法

2025年12月25日 Python 我要评论
typedict(python中类型安全的字典)是python 3.8引入的类型提示工具,用于定义具有固定键集合和各键对应特定类型的字典对象。它允许你为字典的每个键指定值的类型,使静态类型检查器能够更

        typedict(python中类型安全的字典)是python 3.8引入的类型提示工具,用于定义具有固定键集合各键对应特定类型的字典对象。它允许你为字典的每个键指定值的类型,使静态类型检查器能够更准确地验证字典的使用方式。其核心特点如下:

特点说明
字典的键是预定义的字符串必须提前定义好所有键的名称和类型
每个键都有对应的值类型每个键的值都有明确的类型约束
支持必需字段和可选字段可以定义哪些字段必须提供,哪些可选
运行时不强制类型检查python运行时不验证类型,但mypy等工具可以静态检查

一、基本用法

1、定义typeddict

  • python 3.8+ 直接使用 from typing import typeddict
from typing import typeddict
class user(typeddict):
    name: str
    age: int
    is_active: bool
# 创建符合typeddict定义的字典(在注解中声明)
user: user = {
    "name": "张三",
    "age": 30,
    "is_active": true
}

2、在函数中使用

def get_user_info(user: user) -> str:
    return f"用户名:{user['name']},年龄:{user['age']}"
print(get_user_info(user))  # 输出:用户名:张三,年龄:30

3、可选字段处理

(1)使用tool=false

class partialuser(typeddict, total=false):
    name: str
    age: int
    email: str
# 所有字段都是可选的
partial_user: partialuser = {
    "name": "李四"
    # age和email可以不提供
}

(2)使用notrequired

from typing_extensions import notrequired
class userprofile(typeddict):
    name: str                    # 必需字段
    age: int                     # 必需字段
    email: notrequired[str]      # 可选字段
    phone: notrequired[str]      # 可选字段
# 可以不包含可选字段
profile1: userprofile = {
    "name": "王五",
    "age": 25
}
# 也可以包含可选字段
profile2: userprofile = {
    "name": "赵六",
    "age": 28,
    "email": "zhaoliu@example.com"
}

4、注意事项

(1)不强制校验

# 下面这段代码在运行时不会报错
# 但mypy等静态检查器会发出警告
user: user = {
    "name": "错误",  # 这是str,没问题
    "age": "三十",    # 应该是int,类型错误!
    "is_active": true
}

(2)不能在其中定义方法

# typeddict只能定义键的类型,不能定义方法
class badexample(typeddict):
    name: str
    def greet(self) -> str:  # 错误!不允许方法
        return "hello"

二、常见应用场景

1、校验api的响应格式

class apiresponse(typeddict):
    success: bool
    data: notrequired[list[dict]]
    error: notrequired[str]
def process_response(response: apiresponse) -> none:
    if response["success"]:
        if "data" in response:
            print(f"处理数据:{response['data']}")
    else:
        if "error" in response:
            print(f"错误信息:{response['error']}")
# 使用示例
success_resp: apiresponse = {
    "success": true,
    "data": [{"id": 1, "name": "商品1"}]
}
error_resp: apiresponse = {
    "success": false,
    "error": "认证失败"
}

2、函数结构化返回值

class analysisresult(typeddict):
    status: str
    score: float
    details: dict
def analyze_text(text: str) -> analysisresult:
    # 模拟分析逻辑
    return {
        "status": "completed",
        "score": 0.85,
        "details": {"length": len(text), "words": len(text.split())}
    }
result = analyze_text("这是一段测试文本")
# result的类型被明确为analysisresult,ide可以提供智能提示

到此这篇关于python的typeddict基本用法的文章就介绍到这了,更多相关python的typeddict内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com