'FASTAPI: what is the difference in setting optional fields?

i have 2 optional fields publish and ratings, here is my code

  class POST(BaseModel):
    title: str
    content: str
    published: bool = True
    rating: Optional[int] = None

They both result in optional field, so what is the difference between two?

if i try something like this, this also works

class POST(BaseModel):
    title: str
    content: str
    published: bool = True
    rating: int = None


Solution 1:[1]

rating: int = None is not correct. It is a mistake but python simply ignores static typing so here is no difference in behaviour.

For example in Java you will get NullPointerException.

Try to use mypy for typing checks (mypy post_model.py)

Optional case will be completed without errors:

Success: no issues found in 1 source file

However non Optional case will cause error:

post_model.py:7: error: Incompatible types in assignment (expression has type "None", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rzlvmp