Reputation: 784
Im currently working through the fastAPI tutorial, and my environment is setup with black, flake8, bandit and mypy. Everything in the tutorial is working fine, but I keep having to # type: ignore things to make mypy cooperate.
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 then errors:
❯ 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")
I could # type: ignore, but then I lose the type hints and validation in my editor. Am I missing something obvious, or should I just disable mypy for FastAPI projects?
Upvotes: 2
Views: 5180
Reputation: 183
If you are using mypy it could complain with type declarations like:
tax: float = None
With an error like: Incompatible types in assignment (expression has type "None", variable has type "float") In those cases you can use Optional to tell mypy that the value could be None, like:
tax: Optional[float] = None
In the above code, Check out this video, its been explained in this one Base Model explained here
Upvotes: 0
Reputation: 1606
You can use Optional
:
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
That tells mypy
that the value should be of that type but None
is acceptable.
Upvotes: 10