Pydantic: GenericModel does not support generic subclasses

Created on 29 Oct 2019  路  1Comment  路  Source: samuelcolvin/pydantic

Bug

It seems the implementation of pydantic.generics.GenericModel does not support generic subclasses. Example:

import pydantic.generics
import typing

T = typing.TypeVar("T")

class ResponseModel(pydantic.generics.GenericModel, typing.Generic[T]):
    data: List[T]

class PaginatedResponseModel(ResponseModel[T]):
    total_count: int

ConcreteModel = PaginatedReponseModel[dict] # TypeError: Cannot parameterize a concrete instantiation of a generic model

PaginatedReponseModel is erroneously considered "concrete" even though type variables are used as parameters, and not concrete types.
It seems GenericModel.__class_getitem__ does not check if any parameters are TypeVar, like typing.Generic does.

To support generic subclasses, __class_getitem__ should check if all of the parameters are fully concrete type(i.e. any of them are typing.TypeVars, or any of them are generic types that have non-concrete type parameters). If not, a concrete model should not be created.

I would consider this a bug since it does not follow the behavior of other typing.Generic usages, but it could also be a feature request.

Please complete:

  • OS: Ubuntu 18.04.1
  • Python version import sys; print(sys.version): 3.7.1 (default, Oct 22 2018, 11:21:55)
    [GCC 8.2.0]
  • Pydantic version import pydantic; print(pydantic.VERSION): 1.0
bug

Most helpful comment

Yep this is definitely a bug.

In general, I think it should be possible to subclass even concrete generic models. I'm hopeful it's not too hard to implement.

>All comments

Yep this is definitely a bug.

In general, I think it should be possible to subclass even concrete generic models. I'm hopeful it's not too hard to implement.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sm-Fifteen picture sm-Fifteen  路  45Comments

kryft picture kryft  路  35Comments

marlonjan picture marlonjan  路  37Comments

koxudaxi picture koxudaxi  路  25Comments

Gaunt picture Gaunt  路  19Comments