Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
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
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)
over 4 years ago · Santiago Trujillo Relatório

0

I dont think there is any difference except for the fact that by using Optional Key word we explicitly telling that this parameter Is optional both in code and 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:
    ...
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda