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 Apr 6, 2022
1 parent 8997cc5 commit 626c3e3
Show file tree
Hide file tree
Showing 3 changed files with 22 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 @@ -968,8 +968,12 @@ def create_model(
namespace.update(fields)
if __config__:
namespace['Config'] = inherit_config(__config__, BaseConfig)

return type(__model_name, __base__, namespace)
resolved_bases = resolve_bases(__base__)
meta, ns, kwds = prepare_class(__model_name, resolved_bases)
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
14 changes: 14 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,14 @@ 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]), aa=(int, Field(0)))

assert AAModel[int](aa=1).aa == 1

0 comments on commit 626c3e3

Please sign in to comment.