Python开发技巧--类型注解Literal

查看LangChain源码时,发现Literal

python 复制代码
class Document(BaseMedia):
    """Class for storing a piece of text and associated metadata.

    !!! note

        `Document` is for **retrieval workflows**, not chat I/O. For sending text
        to an LLM in a conversation, use message types from `langchain.messages`.

    Example:
        ```python
        from langchain_core.documents import Document

        document = Document(
            page_content="Hello, world!", metadata={"source": "https://example.com"}
        )
        ```
    """

    page_content: str
    """String text."""

    type: Literal["Document"] = "Document"

作用:静态代码检查时,如果type为其他值,即!="Document",会发生报错。 注:在不实际运行程序(不执行代码)的情况下,通过分析源代码的文本结构来找出潜在的错误。

进一步,LangChain 框架中的深层作用

  1. 序列化时的"防伪标签" 当 LangChain 将 Document 对象转换成 JSON 字符串时,type: Literal"Document" 保证了输出的 JSON 里一定会包含这个标签 如下:
python 复制代码
print(f"转换格式后:\n{json.dumps(document1_json, ensure_ascii=False, indent=2)}")

# 转换格式后,{
#   "lc": 1,
#   "type": "constructor",
#   "id": [
#     "langchain",
#     "schema",
#     "document",
#     "Document"
#   ],
#   "kwargs": {
#     "metadata": {
#       "author": "张三",
#       "page": 10
#     },
#     "page_content": "LangChain 是一个用于开发大语言模型应用的框架。",
#     "type": "Document" 
#   }
# }
  1. 配合 Pydantic 的运行时校验 Pydantic 会直接抛出验证错误,防止脏数据污染系统

例子:

python 复制代码
from pydantic import BaseModel
from typing import Literal

class MyClass(BaseModel):
    type: Literal["red"] = "red"

obj = MyClass()
obj.type = "Image"  # ❌ Pydantic 会在运行时抛出 ValidationError
相关推荐
小陈的进阶之路4 小时前
Claude Code辅助测试:导入篇skills
python·自动化
whcyhhh6 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
for_ever_love__6 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76896 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
Niuguangshuo8 小时前
DeepFilterNet 3:端侧实时全带降噪的开源标杆
python
第一程序员8 小时前
AI 辅助编程的 7 个误区:把模型当高级搜索引擎是对它的最大浪费
python·rust·github
Groundwork Explorer9 小时前
W5500 网卡编程初始化与使用指南
python·单片机
逸Y 仙X10 小时前
MCP(模型控制协议)完全指南:从核心概念到实战开发
python·大模型·llm·ai编程·mcp
WILLF11 小时前
前端视角:Python requests vs JS axios
前端·python
哒哒哒52852011 小时前
69. Python: 核心语法-面向对象基础-案例(教务系统)
python