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
相关推荐
卷无止境1 小时前
Python FFI 技术深度解析:ctypes、cffi 与 pybind11 的性能差异与实践挑战
后端·python
郝学胜-神的一滴1 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
万笑佛2 小时前
Python 实现Kafka SASL认证生产消费
python
m0_617493943 小时前
Python OpenCV 透视变换(Perspective Transform)详解与实战
开发语言·python·opencv
小李不困还能学4 小时前
PyCharm下载安装与配置教程
ide·python·pycharm
博观而约取厚积而薄发4 小时前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
imzed4 小时前
使用 Playwright + Pytest 构建 Web UI 自动化测试框架
python·自动化·pytest
普通网友4 小时前
pytest一些常见的插件
开发语言·python·pytest