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

Allow to keep the types as they were and just add a default value #39

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion pydantic_partial/partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def create_partial_model(
base_cls: type[SelfT],
*fields: str,
recursive: bool = False,
optional: bool = True,
) -> type[SelfT]:
# Convert one type to being partial - if possible
def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
Expand Down Expand Up @@ -104,8 +105,15 @@ def _partial_annotation_arg(field_name_: str, field_annotation: type) -> type:
# Construct new field definition
if field_name in fields_:
if model_compat.is_model_field_info_required(field_info):
# Allow to keep the types as they were and just add a
# default value
if optional:
annotation = Optional[field_annotation]
else:
annotation = field_annotation

optional_fields[field_name] = (
Optional[field_annotation],
annotation,
model_compat.copy_model_field_info(
field_info,
default=None, # Set default to None
Expand Down
85 changes: 85 additions & 0 deletions tests/test_optional.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
from typing import Any, Union

import pydantic

import pytest

from pydantic_partial import create_partial_model
from pydantic_partial._compat import PYDANTIC_V1, PYDANTIC_V2


if PYDANTIC_V1:
def _field_is_required(
model: Union[type[pydantic.BaseModel], pydantic.BaseModel],
field_name: str,
) -> bool:
"""Check if a field is required on a pydantic V1 model."""
# noinspection PyDeprecation
return model.__fields__[field_name].required


def _field_get_default(
model: Union[type[pydantic.BaseModel], pydantic.BaseModel],
field_name: str,
) -> tuple[Any, Any]:
"""Return field default info"""
field_info = model.__fields__[field_name]
return field_info.default, field_info.default_factory
elif PYDANTIC_V2:
def _field_is_required(
model: Union[type[pydantic.BaseModel], pydantic.BaseModel],
field_name: str,
) -> bool:
"""Check if a field is required on a pydantic V2 model."""
return model.model_fields[field_name].is_required()


def _field_get_default(
model: Union[type[pydantic.BaseModel], pydantic.BaseModel],
field_name: str,
) -> tuple[Any, Any]:
"""Return field default info"""
field_info = model.model_fields[field_name]
return field_info.default, field_info.default_factory
else:
raise DeprecationWarning("Pydantic has to be in version 1 or 2.")


class Something(pydantic.BaseModel):
name: Union[str, None] = "Joe Doe"
something_else_id: int


PartialSomething = create_partial_model(Something, optional=False)
PartialSomethingOptional = create_partial_model(Something, optional=True)


def test_fields_not_required():
assert _field_is_required(PartialSomething, "name") is False
assert _field_is_required(PartialSomething, "something_else_id") is False


def test_field_defaults():
assert _field_get_default(PartialSomething, "name") == ("Joe Doe", None)
assert _field_get_default(PartialSomething, "something_else_id") == (None, None)


def test_validate_ok():
# It shouldn't be necessary to check that the right default values end
# up in the models. That should already be done by pydantic's own tests.
# We just check that validation succeeds.
PartialSomething()
PartialSomething(name='Jane Doe')
PartialSomething(name=None)
PartialSomething(something_else_id=42)
PartialSomething(name='Jane Doe', something_else_id=42)
PartialSomething(name=None, something_else_id=42)


def test_validate_fail():
with pytest.raises(pydantic.ValidationError):
PartialSomething(something_else_id=None)


def test_validate_optional():
PartialSomethingOptional(something_else_id=None)
Loading