Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create_model support generics model #3946

Merged
merged 2 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
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 is True