Skip to content

Commit

Permalink
create_model support generics model (#3946)
Browse files Browse the repository at this point in the history
* create_model support generics model

* fix change.

Co-authored-by: chenyijian <chenyijian@mycapital.net>
Co-authored-by: Samuel Colvin <samcolvin@gmail.com>
  • Loading branch information
3 people committed Aug 11, 2022
1 parent 4fb872e commit 02a2a8b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
1 change: 1 addition & 0 deletions changes/3945-hot123s.md
@@ -0,0 +1 @@
Support generics model with `create_model`
10 changes: 7 additions & 3 deletions pydantic/main.py
Expand Up @@ -4,7 +4,7 @@
from enum import Enum
from functools import partial
from pathlib import Path
from types import FunctionType
from types import FunctionType, prepare_class, resolve_bases
from typing import (
TYPE_CHECKING,
AbstractSet,
Expand Down Expand Up @@ -996,8 +996,12 @@ def create_model(
namespace.update(fields)
if __config__:
namespace['Config'] = inherit_config(__config__, BaseConfig)

return type(__model_name, __base__, namespace, **__cls_kwargs__)
resolved_bases = resolve_bases(__base__)
meta, ns, kwds = prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__)
if resolved_bases is not __base__:
ns['__orig_bases__'] = __base__
namespace.update(ns)
return meta(__model_name, resolved_bases, namespace, **kwds)


_missing = object()
Expand Down
17 changes: 17 additions & 0 deletions tests/test_create_model.py
@@ -1,6 +1,9 @@
from typing import Generic, TypeVar

import pytest

from pydantic import BaseModel, Extra, Field, ValidationError, create_model, errors, validator
from pydantic.generics import GenericModel


def test_create_model():
Expand Down Expand Up @@ -205,3 +208,17 @@ class Config:

m2 = create_model('M2', __config__=Config, a=(str, Field(...)))
assert m2.schema()['properties'] == {'a': {'title': 'A', 'description': 'descr', 'type': 'string'}}


def test_generics_model():
T = TypeVar('T')

class TestGenericModel(GenericModel):
pass

AAModel = create_model(
'AAModel', __base__=(TestGenericModel, Generic[T]), __cls_kwargs__={'orm_mode': True}, aa=(int, Field(0))
)
result = AAModel[int](aa=1)
assert result.aa == 1
assert result.__config__.orm_mode is True

0 comments on commit 02a2a8b

Please sign in to comment.