使用 MyPy 的项目中的 FastAPI/Pydantic

Jus*_*n S 1 python mypy pydantic fastapi

我目前正在学习 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
Run Code Online (Sandbox Code Playgroud)

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

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

Seb*_*rez 5

您可以使用Optional

from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
Run Code Online (Sandbox Code Playgroud)

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