Skip to content

Do not inherit config in model fields that are themselves of type model #612

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

Merged
merged 1 commit into from
May 19, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions pydantic_core/core_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ def dict_not_none(**kwargs: Any) -> Any:
class CoreConfig(TypedDict, total=False):
title: str
strict: bool
# higher priority configs take precedence of over lower, if priority matches the two configs are merged, default 0
config_choose_priority: int
# if configs are merged, which should take precedence, default 0, default means child takes precedence
config_merge_priority: int
# settings related to typed dicts, model fields, dataclass fields
extra_fields_behavior: ExtraBehavior
typed_dict_total: bool # default: True
Expand Down
41 changes: 0 additions & 41 deletions src/build_tools.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::borrow::Cow;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;

Expand Down Expand Up @@ -281,43 +280,3 @@ impl ExtraBehavior {
Ok(res)
}
}

pub(crate) fn build_model_config<'a>(
py: Python<'a>,
schema: &'a PyDict,
parent_config: Option<&'a PyDict>,
) -> PyResult<Option<&'a PyDict>> {
let child_config: Option<&PyDict> = schema.get_as(intern!(py, "config"))?;
match (parent_config, child_config) {
(Some(parent), None) => Ok(Some(parent)),
(None, Some(child)) => Ok(Some(child)),
(None, None) => Ok(None),
(Some(parent), Some(child)) => {
let key = intern!(py, "config_choose_priority");
let parent_choose: i32 = parent.get_as(key)?.unwrap_or_default();
let child_choose: i32 = child.get_as(key)?.unwrap_or_default();
match parent_choose.cmp(&child_choose) {
Ordering::Greater => Ok(Some(parent)),
Ordering::Less => Ok(Some(child)),
Ordering::Equal => {
let key = intern!(py, "config_merge_priority");
let parent_merge: i32 = parent.get_as(key)?.unwrap_or_default();
let child_merge: i32 = child.get_as(key)?.unwrap_or_default();
match parent_merge.cmp(&child_merge) {
Ordering::Greater => {
let new_child = child.copy()?;
new_child.update(parent.as_mapping())?;
Ok(Some(new_child))
}
// otherwise child is the winner
_ => {
let new_parent = parent.copy()?;
new_parent.update(child.as_mapping())?;
Ok(Some(new_parent))
}
}
}
}
}
}
}
6 changes: 3 additions & 3 deletions src/serializers/type_serializers/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use pyo3::{intern, PyTraverseError, PyVisit};

use ahash::AHashMap;

use crate::build_tools::{build_model_config, py_error_type, ExtraBehavior, SchemaDict};
use crate::build_tools::{py_error_type, ExtraBehavior, SchemaDict};
use crate::definitions::DefinitionsBuilder;

use super::{
Expand Down Expand Up @@ -74,13 +74,13 @@ impl BuildSerializer for ModelSerializer {

fn build(
schema: &PyDict,
config: Option<&PyDict>,
_config: Option<&PyDict>,
definitions: &mut DefinitionsBuilder<CombinedSerializer>,
) -> PyResult<CombinedSerializer> {
let py = schema.py();

// models ignore the parent config and always use the config from this model
let config = build_model_config(py, schema, config)?;
let config = schema.get_as(intern!(py, "config"))?;

let class: &PyType = schema.get_as_req(intern!(py, "cls"))?;
let sub_schema: &PyDict = schema.get_as_req(intern!(py, "schema"))?;
Expand Down
6 changes: 3 additions & 3 deletions src/validators/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use pyo3::prelude::*;
use pyo3::types::{PyDict, PySet, PyString, PyTuple, PyType};
use pyo3::{ffi, intern};

use crate::build_tools::{build_model_config, py_err, schema_or_config_same, SchemaDict};
use crate::build_tools::{py_err, schema_or_config_same, SchemaDict};
use crate::errors::{ErrorType, ValError, ValResult};
use crate::input::{py_error_on_minusone, Input, InputType};
use crate::recursion_guard::RecursionGuard;
Expand Down Expand Up @@ -64,12 +64,12 @@ impl BuildValidator for ModelValidator {

fn build(
schema: &PyDict,
config: Option<&PyDict>,
_config: Option<&PyDict>,
definitions: &mut DefinitionsBuilder<CombinedValidator>,
) -> PyResult<CombinedValidator> {
let py = schema.py();
// models ignore the parent config and always use the config from this model
let config = build_model_config(py, schema, config)?;
let config = schema.get_as(intern!(py, "config"))?;

let class: &PyType = schema.get_as_req(intern!(py, "cls"))?;
let sub_schema: &PyAny = schema.get_as_req(intern!(py, "schema"))?;
Expand Down
124 changes: 0 additions & 124 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,130 +68,6 @@ def test_field_priority_model():
assert v.isinstance_python({'f': 'test long'}) is False


def test_parent_priority():
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
'config': {'str_min_length': 2, 'str_max_length': 10},
},
{'str_max_length': 5, 'config_choose_priority': 1},
)
r = plain_repr(v)
assert 'min_length:Some(2)' not in r # child is ignored
assert 'max_length:Some(5)' in r
assert v.isinstance_python({'f': 'test'}) is True
assert v.isinstance_python({'f': 't'}) is True
assert v.isinstance_python({'f': 'test long'}) is False


def test_child_priority():
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
'config': {'str_max_length': 5, 'config_choose_priority': 1},
},
{'str_min_length': 2, 'str_max_length': 10},
)
r = plain_repr(v)
assert 'min_length:Some(2)' not in r # parent is ignored
assert 'max_length:Some(5)' in r
assert v.isinstance_python({'f': 'test'}) is True
assert v.isinstance_python({'f': 't'}) is True
assert v.isinstance_python({'f': 'test long'}) is False


def test_merge_child_wins():
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
'config': {'str_max_length': 5},
},
{'str_min_length': 2, 'str_max_length': 10},
)
r = plain_repr(v)
assert 'min_length:Some(2)' in r
assert 'max_length:Some(5)' in r
assert v.isinstance_python({'f': 'test'}) is True
assert v.isinstance_python({'f': 't'}) is False
assert v.isinstance_python({'f': 'test long'}) is False


def test_merge_parent_wins():
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
'config': {'str_max_length': 5},
},
{'str_min_length': 2, 'str_max_length': 10, 'config_merge_priority': 1},
)
r = plain_repr(v)
assert 'min_length:Some(2)' in r
assert 'max_length:Some(10)' in r
assert 'max_length:Some(5)' not in r
assert v.isinstance_python({'f': 'test'}) is True
assert v.isinstance_python({'f': 't'}) is False
assert v.isinstance_python({'f': 'test long'}) is True
assert v.isinstance_python({'f': 'test very long'}) is False


def test_sub_model_merge():
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {
'type': 'model-fields',
'fields': {
'f': {'type': 'model-field', 'schema': {'type': 'str'}},
'sub_model': {
'type': 'model-field',
'schema': {
'type': 'model',
'cls': MyModel,
'schema': {
'type': 'model-fields',
'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}},
},
'config': {'str_max_length': 6, 'str_to_upper': True},
},
},
},
},
'config': {'str_min_length': 1, 'str_max_length': 4},
}
)
# f should have bounds 1-4
# sub_model.f should have bounds 1-6, and should be upper-cased
output = v.validate_python({'f': 'test', 'sub_model': {'f': 'tests'}})
assert output == IsInstance(MyModel) & HasAttributes(f='test', sub_model=HasAttributes(f='TESTS'))
with pytest.raises(ValidationError) as exc_info:
v.validate_python({'f': 'tests', 'sub_model': {'f': ''}})
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_too_long',
'loc': ('f',),
'msg': 'String should have at most 4 characters',
'input': 'tests',
'ctx': {'max_length': 4},
},
{
'type': 'string_too_short',
'loc': ('sub_model', 'f'),
'msg': 'String should have at least 1 characters',
'input': '',
'ctx': {'min_length': 1},
},
]


@pytest.mark.parametrize(
'config,float_field_schema,input_value,expected',
[
Expand Down