Python中类型注解Literal的实现
查看LangChain源码时,发现Literal:
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 框架中的深层作用
序列化时的“防伪标签” 当 LangChain 将 Document 对象转换成 JSON 字符串时,type: Literal["Document"] 保证了输出的 JSON 里一定会包含这个标签 如下:
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"
# }
# }
配合 Pydantic 的运行时校验 Pydantic 会直接抛出验证错误,防止脏数据污染系统
例子:
from pydantic import BaseModel
from typing import Literal
class MyClass(BaseModel):
type: Literal["red"] = "red"
obj = MyClass()
obj.type = "Image" # ❌ Pydantic 会在运行时抛出 ValidationError
到此这篇关于Python中类型注解Literal的实现的文章就介绍到这了,更多相关Python 类型注解Literal内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python 实现 hive中类似 lateral view explode的功能示例
这篇文章主要介绍了python 实现 hive中类似 lateral view explode的功能示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-05-05
Python 实现将numpy中的nan和inf,nan替换成对应的均值
这篇文章主要介绍了Python 实现将numpy中的nan和inf,nan替换成对应的均值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-06-06


最新评论