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

795
Visualizações
Mypy + FastAPI response_model

I've been tasked with handling the update from Mypy 0.770 to 0.870 in our FastAPI project, and this has produced an error that I can't quite wrap my head around. My endpoint can return two different models based on some condition, and this was denoted as follows the endpont decorator:

@router.get("/", response_model=Union[Model1, Model2])

Mypy 0.870 now complains about this, stating that

Argument "response_model" to "get" of "APIRouter" has incompatible type "object"; expected "Optional[Type[Any]]"

Setting it to single types, such as Model1 or even str removes the error. Any however, does not work.

Now, looking into the get method, I see that the response_model argument is typed as Type[Any], which I assume must be a pointer.

How I can define non-simple return models for my API, and make Mypy happy?

edit: I tried to reproduce the problem in a smaller frame, but couldn't. The following code works fine:

from typing import Any, Type, Union


def test1(var, response_model: Type[Any]):
    print(f"Accepted Type[Any], {var}")

def test2(var, response_model: Union[dict, set]):
    print(f"Accepted Union, {var}")

def main():
    test1('test1', response_model=Union[dict, set])
    test2('test2', response_model=Union[dict, set])

if __name__ == '__main__':
    main()
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This is a compatibility issue introduced in newer versions of mypy. There is an open issue on Github about this topic: https://github.com/tiangolo/fastapi/issues/2279

In the discussion they provide the following workarounds:

  • Using a different approach to create a type alias:

    NewModel = TypeVar('NewModel',Model1,Model2)

  • Creating a new Pydantic Model :

    class NewModel(BaseModel):
         __root__: Union[Model1, Model2]
    
over 4 years ago · Santiago Trujillo Relatório

0

Type[] of something means a not instantiated class of this type, while Model1 here will mean an instance of a Model1 class or an instance of anything that inherits from Model1.

Nonetheless, the error message is enigmatic.

What python -v are you using? Typing is a new thing in a python world and things might change between python versions as well. If you bumped mypy version it might be good to upgrade python as well as they go together.

Also, what fastapi version are you using? I'd try bump it to the latest, 0.55.1, as well. Tiangolo himself wrote they have had a bug with typing

source

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