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

Fix pydantic dataclass problem with dataclasses.field default #7898

Merged
merged 2 commits into from Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 5 additions & 1 deletion pydantic/_internal/_fields.py
Expand Up @@ -248,7 +248,11 @@ def collect_dataclass_fields(
if is_classvar(ann_type):
continue

if not dataclass_field.init and dataclass_field.default_factory == dataclasses.MISSING:
if (
not dataclass_field.init
and dataclass_field.default == dataclasses.MISSING
and dataclass_field.default_factory == dataclasses.MISSING
):
# TODO: We should probably do something with this so that validate_assignment behaves properly
# Issue: https://github.com/pydantic/pydantic/issues/5470
continue
Expand Down
17 changes: 16 additions & 1 deletion tests/test_dataclasses.py
Expand Up @@ -24,6 +24,7 @@
PydanticDeprecatedSince20,
PydanticUndefinedAnnotation,
PydanticUserError,
RootModel,
TypeAdapter,
ValidationError,
ValidationInfo,
Expand Down Expand Up @@ -2459,7 +2460,21 @@ def test_dataclass_field_default_factory_with_init():
class Model:
x: int = dataclasses.field(default_factory=lambda: 3, init=False)

assert Model().x == 3
m = Model()
assert 'x' in Model.__pydantic_fields__
assert m.x == 3
assert RootModel[Model](m).model_dump() == {'x': 3}


def test_dataclass_field_default_with_init():
@pydantic.dataclasses.dataclass
class Model:
x: int = dataclasses.field(default=3, init=False)

m = Model()
assert 'x' in Model.__pydantic_fields__
assert m.x == 3
assert RootModel[Model](m).model_dump() == {'x': 3}


def test_metadata():
Expand Down