mypy annotation and constrained lists recommendation
See original GitHub issueQuestion
Please complete:
- OS: Debian 10 (
python:3.7-slim
Docker image) - Python version: 3.7.5
- Pydantic version 0.32.2
Hello! I’m hoping to find the best practice for the interaction between mypy
checks and the ConstrainedList
/conlist()
pydantic
types. For the MWE below, we’re expecting a BaseModel
taking a fixed-length list of floats (this is used as a request body in FastAPI
):
from pydantic import BaseModel, conlist
class EmbeddingRequest(BaseModel):
embedding: conlist(float, min_items=100, max_items=100)
which behaves as expected, but complains when run through mypy checks (same error as in the older #239 issue). From #862 it sounds like it’s still on deck to add improvements to documentation for mypy+constrained types, so hopefully this can help. Alternately, I suppose this might be something that is resolved in v1.0/1.1 - for the time being I’m pinned to 0.32.2 for FastAPI compatibility, but I doubt that will last long.
Older issues propose a few options:
option 1
per #239,
from typing import List, Type
from pydantic import BaseModel, conlist
Vector: Type[List[float]] = conlist(float, min_items=100, max_items=100)
class EmbeddingRequest(BaseModel):
embedding: Vector
runs, but complains that Vector
is not valid as a type (and defining it as type ConstrainedList
rather than List[float]
per #156 fails for type mismatch).
option 2
also in #239 , explicitly subclassing the type
from pydantic import BaseModel, ConstrainedList
class Vector(ConstrainedList):
item_type = float
min_items = 100
max_items = 100
__args__ = [float]
class EmbeddingRequest(BaseModel):
embedding: Vector
functions properly and passes mypy
, but forcing the explicit __args__
overloading for it to behave properly relative to conlist()
feels evil to me.
option 3
just punt and add a type: ignore
flag on the original conlist
call.
Any advice on this would be much appreciated!
Issue Analytics
- State:
- Created 4 years ago
- Reactions:8
- Comments:16 (11 by maintainers)
If you (as I’m) don’t get what does it means: “With the new Annotated syntax, it should now be possible to make it work properly”
In Python 3.9+:
oh, that probably doesn’t work but would be the best solution,
The other thing to do is
or something.