I’m using VSCode and the default Python Language Support extension from MS, whcih lints with Pylance. I have a Python 3.12 FastAPI project which uses type annotations to indicate which models should be returned as responses from the handlers using the pattern suggested by the FastAPI docs (https://fastapi.tiangolo.com/tutorial/response-model/#return-type-and-data-filtering). There are no errors when the code is run and the app works correctly, returning the correct results in the correct models. However, I get Pylance linting errors that my function return types are not compatible with my returns.
Here are my FastAPI SQLModel/Pydantic models:
class PetBase(SQLModel):
name: str
class Pet(PetBase, table=True):
id: str
class PetOutgoing(PetBase):
id: str
Here’s my handler:
@router.get("/{pet_id}")
def retrieve_one(pet_id: str) -> PetOutgoing:
pet: Pet = get_pet_by_id(pet_id)
return pet
This endpoint returns the PetOutgoing
model. FastAPI converts it on the fly.
But here’s the Pylance linting error I get.
Expression of type "Pet" is incompatible with return type "PetOutgoing"
"Pet" is incompatible with "PetOutgoing" PylancereportReturnType
(variable) pet: Pet
What am I doing wrong?