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
相关推荐
“AI国潮设计-小江”10 小时前
AIGC实战:Python+SDXL批量生成英歌舞IP立牌,解锁猪猪蛋糕“反差萌”流量密码(附完整API源码)
开发语言·人工智能·python·prompt·aigc
成信吴彦祖11 小时前
当前专业的无人机RID侦测主站供应商主要有哪些
python·1024程序员节
编程的一拳超人11 小时前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
fanruitian11 小时前
python anaconda jupyter notebook
python
云和数据.ChenGuang11 小时前
Python 菜鸟入门:字典(dict)类型详解与 CRUD 实战案例
开发语言·人工智能·python
小白今天也很酷11 小时前
MCXN947更新板载DAP_Link固件的方法
c语言·python·单片机·ubuntu·excel·1024程序员节
小羊没烦恼!11 小时前
.NET无侵入自动化探针原理和主流实现
运维·开发语言·javascript·python·自动化·.net·1024程序员节
立康科普11 小时前
含多肽钙的补钙产品是什么?和普通钙片有什么区别?
python·1024程序员节
“AI国潮设计-小江”20 小时前
【AIGC实战】Python+SDXL批量生成“潮汕英歌舞不倒翁”IP | 角色一致性与多场景融合方案,附完整代码
开发语言·人工智能·python·prompt·aigc
Linux_cy20 小时前
服务器管理工具哪个好用?我用了七八个
运维·服务器·javascript·python·ssh·面板·gmssh