Pydantic: Model Validation Issue for Nested, Optional, Generic Model

Created on 30 Dec 2020  路  1Comment  路  Source: samuelcolvin/pydantic

Checks

  • [x] I added a descriptive title to this issue
  • [x] I have searched (google, github) for similar issues and couldn't find anything
  • [x] I have read and followed the docs and still think this is a bug

Bug

The code below outputs:

Caught A
Missed B

Although it should catch both validations. Generic model which is marked as optional seems to fail type checks, and produces "Any" type instead.

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.7.3
            pydantic compiled: True
                 install path: /opt/virtualenvs/python3/lib/python3.8/site-packages/pydantic
               python version: 3.8.7 (default, Dec 21 2020, 20:10:35)  [GCC 7.5.0]
                     platform: Linux-5.4.0-1019-gcp-x86_64-with-glibc2.27
     optional deps. installed: ['typing-extensions']
from typing import TypeVar, Generic, Optional, List
from pydantic import BaseModel
from pydantic.generics import GenericModel


DataT = TypeVar('DataT')


class Data(BaseModel):
  foo: str


# --- WORKS ---

class APIContentS(GenericModel, Generic[DataT]):
    """Second-level for the API response. i.e. the content"""
    data: DataT
    message: Optional[str] = None


class APIResponseS(GenericModel, Generic[DataT]):
    """Base API response model"""
    payload: APIContentS[DataT]
    is_successful: bool = True


try:
  model = APIResponseS[List[Data]](
    payload=APIContentS(
      data=[{'bar': True}]
    )
  )
  print("Missed A")
except:
  print("Caught A")


# --- FAILS ---

class APIContent(GenericModel, Generic[DataT]):
    """Second-level for the API response. i.e. the content"""
    data: Optional[DataT]
    message: Optional[str] = None


class APIResponse(GenericModel, Generic[DataT]):
    """Base API response model"""
    payload: APIContent[DataT]
    is_successful: bool = True


try:
  model = APIResponse[List[Data]](
    payload=APIContent(
      data=[{'bar': True}]
    )
  )
  print("Missed B")
except:
  print("Caught B")
bug

Most helpful comment

Hi @Mazyod
There is already an opened PR #1989 solving a lot of issues on generic models.
It also solves your issue :)
The fix will be available in pydantic 1.8 for sure 馃憤
Happy new year 馃帀

>All comments

Hi @Mazyod
There is already an opened PR #1989 solving a lot of issues on generic models.
It also solves your issue :)
The fix will be available in pydantic 1.8 for sure 馃憤
Happy new year 馃帀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

drpoggi picture drpoggi  路  3Comments

sbv-trueenergy picture sbv-trueenergy  路  3Comments

timonbimon picture timonbimon  路  3Comments

krzysieqq picture krzysieqq  路  3Comments

AlbertMukhammadiev picture AlbertMukhammadiev  路  3Comments