tengo 2 campos opcionales publicar y calificaciones, aquí está mi código
class POST(BaseModel): title: str content: str published: bool = True rating: Optional[int] = NoneAmbos dan como resultado un campo opcional, entonces, ¿cuál es la diferencia entre dos?
si intento algo como esto, esto también funciona
class POST(BaseModel): title: str content: str published: bool = True rating: int = Nonerating: int = None no es correcto. Es un error, pero Python simplemente ignora la escritura estática, por lo que no hay diferencia en el comportamiento.
Por ejemplo, en Java obtendrá NullPointerException .
Intente usar mypy para escribir cheques ( mypy post_model.py )
El caso Optional se completará sin errores:
Success: no issues found in 1 source file Sin embargo, el caso no Optional causará un 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)No creo que haya ninguna diferencia, excepto por el hecho de que al usar la palabra clave opcional, decimos explícitamente que este parámetro es opcional tanto en el código como en la arrogancia.
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: ...