pydantic 与 mypy 的使用

And*_*kin 4 python mypy pydantic fastapi

我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)

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

我的输出:

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")
Run Code Online (Sandbox Code Playgroud)

SCo*_*vin 5

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

pydantic 的第 1 版应该在几天内发布,其中FieldSchema在 v1中替换)是一个返回的函数Any,应该可以解决这个问题。

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