Skip to content

Commit

Permalink
create_model support generics model
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyijian committed Aug 11, 2022
1 parent 4fb872e commit c088109
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
create_model support generics model
10 changes: 7 additions & 3 deletions pydantic/main.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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 == True

0 comments on commit c088109

Please sign in to comment.