FASTAPI:设置可选字段有什么区别?

FASTAPI: what is the difference in setting optional fields?

我有 2 个可选字段 publish 和 ratings,这是我的代码

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

它们都是可选字段,那么两者有什么区别?

如果我尝试这样的事情,这也有效

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

除了通过使用 Optional 关键字我们明确告诉这个参数在代码和 swagger 中都是可选的之外,我认为没有任何区别。

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

def foo(arg: int = 0) -> None:
    ...
On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

def foo(arg: Optional[int] = None) -> None:
    ...

rating: int = None 不正确。这是一个错误,但是 python 只是忽略了静态类型,所以这里的行为没有区别。

例如在 Java 你会得到 NullPointerException.

尝试使用 mypy 进行打字检查 (mypy post_model.py)

Optional 案例将无误地完成:

Success: no issues found in 1 source file

但是非Optional 的情况会导致错误:

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)