我正在尝试使用 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/