python - pydantic 与 mypy 的使用

标签 python mypy fastapi pydantic

我正在尝试使用 FastAPI 编写一个应用程序,该应用程序大量使用 pydantic。我还想使用 mypy 对我的代码进行类型检查.如何在没有冲突的情况下为 pydantic 和 mypy 使用类型注释?

我知道 type: ignore评论,但在我看来这是某种作弊:)

例子:

from pydantic import BaseModel, Schema


class UsersQuery(BaseModel):
    limit: int = Schema(default=100, gt=0, le=100)
    offset: int = Schema(default=0, ge=0)

此代码工作正常,但类型检查失败。

我的输出:
error: Incompatible types in assignment (expression has type "Schema", variable has type "int")
error: Incompatible types in assignment (expression has type "Schema", variable has type "int")

最佳答案

type: ignore是目前唯一的解决方案。

pydantic 的第 1 版应该会在几天内发布,其中 Field (取代 v1 中的 Schema)是一个返回 Any 的函数这应该解决这个问题。

tl; dr等待fastapi发布并支持v1,您的问题应该得到解决。

关于python - pydantic 与 mypy 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486316/

相关文章:

python - Snorkel:我可以在数据集中使用不同的特征来生成标签函数 VS 训练分类器吗?

Python - 从电子邮件附件下载 excel 文件然后解析它

python - 如何让 mypy 识别较新版本的 python?

python - PyCharm 使用 Mypy 吗?

python - Mypy:在映射类型中使用联合无法按预期工作

python - 为什么使用 FastAPI 上传图片时会出现 "Unprocessable Entity"错误?

python - 使用另一个数据帧中的系数将方程应用于数据帧

python - issubclass(C, Mapping) 的行为不符合预期

python - 为什么我会收到 CORS 错误原因 : CORS request did not succeed

json - 在 FastAPI 应用程序中将 JSON 转换为 DataFrame