3

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.