Skip to content

Commit

Permalink
Raise error when Pydantic dataclasses are used on models
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed May 3, 2024
1 parent 6282204 commit 30c1995
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pydantic/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

from ._internal import _config, _decorators, _typing_extra
from ._internal import _dataclasses as _pydantic_dataclasses
from ._internal._utils import is_model_class
from ._migration import getattr_migration
from .config import ConfigDict
from .errors import PydanticUserError
from .fields import Field, FieldInfo

if TYPE_CHECKING:
Expand Down Expand Up @@ -190,6 +192,12 @@ def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
Returns:
A Pydantic dataclass.
"""
if is_model_class(cls):
raise PydanticUserError(
f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
code=None,
)

original_cls = cls

config_dict = config
Expand Down
10 changes: 10 additions & 0 deletions tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@
from pydantic.json_schema import model_json_schema


def test_cannot_create_dataclass_from_basemodel_subclass():
msg = 'Cannot create a Pydantic dataclass from SubModel as it is already a Pydantic model'

with pytest.raises(PydanticUserError, match=msg):

@pydantic.dataclasses.dataclass
class SubModel(BaseModel):
pass


def test_simple():
@pydantic.dataclasses.dataclass
class MyDataclass:
Expand Down

0 comments on commit 30c1995

Please sign in to comment.