Pydantic: Feature Request: generic/parameterized models

Created on 27 May 2019  路  6Comments  路  Source: samuelcolvin/pydantic


Feature Request

It would be nice to be able construct models by composition, instead of just static descriptions and inheritance-based extension. What I mean by "composition", is being able to define a partial, parameterized model, which can yield new, complete models/validators by combining with other models/validators. This could be done by exploiting something like typing.Generic, e.g.:

import typing
import pydantic

T = typing.TypeVar("T")

class Response(pydantic.GenericModel[T]):
    data: T = ...
    total_count: int = None

and then, one could use Response[MyModel] or Response[List[MyModel]] as validators.

I think support for generic is mentioned in https://github.com/samuelcolvin/pydantic/issues/380.

feature request

Most helpful comment

As a result of @dmontagu's magic it looks like this should be possible.

All 6 comments

looks like this would be extremely difficult to accomplish.

You could achieve roughly the same thing with create_model it would be much uglier but more powerful.

Unless lots of people want this, I'd rather not.

Comment here if you really need this.

You could achieve roughly the same thing with create_model it would be much uglier but more powerful.

Or of course by simple inheritance if you only need a few/defined variants of Response.

Yes, I'm taking the approach of using a function to define that kind of model dynamically, e.g.

import pydantic
from typing import Union, Type
def response(data_type: Union[type, Type[pydantic.BaseModel]]) -> Type[pydantic.BaseModel]:
    return pydantic.create_model(getattr(data_type, "__name__", str(data_type))+"Response", data=(data_type, ...), ...)

I guess this is fine.

Too much work for me unless someone can find an easy way of doing this or wants a big job...

As a result of @dmontagu's magic it looks like this should be possible.

Wow, that's awesome. Thanks @samuelcolvin, @dmontagu .

Was this page helpful?
0 / 5 - 0 ratings