Python的TypedDict基本用法
TypeDict(Python中類型安全的字典)是Python 3.8引入的類型提示工具,用于定義具有固定鍵集合和各鍵對(duì)應(yīng)特定類型的字典對(duì)象。它允許你為字典的每個(gè)鍵指定值的類型,使靜態(tài)類型檢查器能夠更準(zhǔn)確地驗(yàn)證字典的使用方式。其核心特點(diǎn)如下:
| 特點(diǎn) | 說明 |
|---|---|
| 字典的鍵是預(yù)定義的字符串 | 必須提前定義好所有鍵的名稱和類型 |
| 每個(gè)鍵都有對(duì)應(yīng)的值類型 | 每個(gè)鍵的值都有明確的類型約束 |
| 支持必需字段和可選字段 | 可以定義哪些字段必須提供,哪些可選 |
| 運(yùn)行時(shí)不強(qiáng)制類型檢查 | Python運(yùn)行時(shí)不驗(yàn)證類型,但mypy等工具可以靜態(tài)檢查 |
一、基本用法
1、定義TypedDict
- Python 3.8+ 直接使用
from typing import TypedDict
from typing import TypedDict
class User(TypedDict):
name: str
age: int
is_active: bool
# 創(chuàng)建符合TypedDict定義的字典(在注解中聲明)
user: User = {
"name": "張三",
"age": 30,
"is_active": True
}2、在函數(shù)中使用
def get_user_info(user: User) -> str:
return f"用戶名:{user['name']},年齡:{user['age']}"
print(get_user_info(user)) # 輸出:用戶名:張三,年齡:303、可選字段處理
(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、注意事項(xiàng)
(1)不強(qiáng)制校驗(yàn)
# 下面這段代碼在運(yùn)行時(shí)不會(huì)報(bào)錯(cuò)
# 但mypy等靜態(tài)檢查器會(huì)發(fā)出警告
user: User = {
"name": "錯(cuò)誤", # 這是str,沒問題
"age": "三十", # 應(yīng)該是int,類型錯(cuò)誤!
"is_active": True
}
(2)不能在其中定義方法
# TypedDict只能定義鍵的類型,不能定義方法
class BadExample(TypedDict):
name: str
def greet(self) -> str: # 錯(cuò)誤!不允許方法
return "Hello"
二、常見應(yīng)用場(chǎng)景
1、校驗(yàn)API的響應(yīng)格式
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"處理數(shù)據(jù):{response['data']}")
else:
if "error" in response:
print(f"錯(cuò)誤信息:{response['error']}")
# 使用示例
success_resp: APIResponse = {
"success": True,
"data": [{"id": 1, "name": "商品1"}]
}
error_resp: APIResponse = {
"success": False,
"error": "認(rèn)證失敗"
}2、函數(shù)結(jié)構(gòu)化返回值
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("這是一段測(cè)試文本")
# result的類型被明確為AnalysisResult,IDE可以提供智能提示到此這篇關(guān)于Python的TypedDict基本用法的文章就介紹到這了,更多相關(guān)Python的TypedDict內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python生態(tài)圈圖像格式轉(zhuǎn)換問題(推薦)
在Python生態(tài)圈里,最常用的圖像庫(kù)是PIL——盡管已經(jīng)被后來的pillow取代,但因?yàn)閜illow的API幾乎完全繼承了PIL,所以大家還是約定俗成地稱其為PIL。這篇文章主要介紹了Python生態(tài)圈圖像格式轉(zhuǎn)換問題,需要的朋友可以參考下2019-12-12
查看jupyter notebook每個(gè)單元格運(yùn)行時(shí)間實(shí)例
這篇文章主要介紹了查看jupyter notebook每個(gè)單元格運(yùn)行時(shí)間實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python優(yōu)秀開源項(xiàng)目Rich源碼解析的流程分析
這篇文章主要介紹了Python優(yōu)秀開源項(xiàng)目Rich源碼解析,本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
django 實(shí)現(xiàn)電子支付功能的示例代碼
這篇文章主要介紹了django 實(shí)現(xiàn)電子支付功能的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07
探索Python int()函數(shù)傳入中文或者字符串會(huì)發(fā)生什么
這篇文章主要為大家介紹了Python int()函數(shù)傳入中文或者字符串會(huì)發(fā)生什么,詳細(xì)討論int()函數(shù)的常規(guī)使用以及它如何處理異常輸入,特別是涉及字符串和中文字符的情況2024-01-01

