首页 > 解决方案 > 使用 MyPy 的项目中的 FastAPI/Pydantic

问题描述

我目前正在学习 fastAPI 教程,我的环境设置为 black、flake8、bandit 和 mypy。本教程中的所有内容都运行良好,但我一直不得不 # type: ignore things 让 mypy 合作。

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


@app.post("/items/")
async def create_items(item: Item) -> Item:
    return item

Mypy 然后错误:

 ❯ mypy main.py                                                                                                                                                                                                 [14:34:08]
main.py:9: error: Incompatible types in assignment (expression has type "None", variable has type "str")
main.py:11: error: Incompatible types in assignment (expression has type "None", variable has type "float") 

我可以 # type: ignore ,但是我在编辑器中丢失了类型提示和验证。我是否遗漏了一些明显的东西,还是应该为 FastAPI 项目禁用 mypy?

标签: pythonmypypydanticfastapi

解决方案


您可以使用Optional

from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

mypy表明该值应该属于该类型,但None可以接受。


推荐阅读