5

I'm trying to write an application using FastAPI which intensively uses pydantic. Also I would like to type-check my code using mypy. How can I use type annotations for pydantic and mypy without conflict?

I know about type: ignore comments but in my opinion it's some kind of cheating :)

Example:

from pydantic import BaseModel, Schema


class UsersQuery(BaseModel):
    limit: int = Schema(default=100, gt=0, le=100)
    offset: int = Schema(default=0, ge=0)

This code works correctly but fails type checking.

mypy output:

error: Incompatible types in assignment (expression has type "Schema", variable has type "int")
error: Incompatible types in assignment (expression has type "Schema", variable has type "int")
Andrey Semakin
  • 2,032
  • 1
  • 23
  • 50

1 Answers1

5

type: ignore is the only solution for now.

Version 1 of pydantic should be released in a few days where Field (which replaces Schema in v1) is a function returning Any which should fix this problem.

tl;dr wait for v1 to be released and supported by fastapi and your problem should be solved.

SColvin
  • 11,584
  • 6
  • 57
  • 71