Skip to content

Short circuit non-tagged unions #430

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

Closed
wants to merge 2 commits into from
Closed
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
9 changes: 8 additions & 1 deletion src/input/return_enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,16 @@ fn validate_iter_to_vec<'a, 's>(
match validator.validate(py, item, extra, slots, recursion_guard) {
Ok(item) => output.push(item),
Err(ValError::LineErrors(line_errors)) => {
if !extra.exhaustive {
return Err(ValError::Omit);
}
errors.extend(line_errors.into_iter().map(|err| err.with_outer_location(index.into())));
}
Err(ValError::Omit) => (),
Err(ValError::Omit) => {
if !extra.exhaustive {
return Err(ValError::Omit);
}
}
Comment on lines +67 to +76
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just an example, I think we'd have to implement this in other places, wherever it makes sense.

Err(err) => return Err(err),
}
}
Expand Down
1 change: 1 addition & 0 deletions src/validators/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ impl InternalValidator {
field: self.field.as_deref(),
strict: self.strict,
context: self.context.as_ref().map(|data| data.as_ref(py)),
exhaustive: true,
};
self.validator
.validate(py, input, &extra, &self.slots, &mut self.recursion_guard)
Expand Down
14 changes: 14 additions & 0 deletions src/validators/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ impl SchemaValidator {
field: Some(field.as_str()),
strict,
context,
exhaustive: true,
};
let r = self
.validator
Expand Down Expand Up @@ -450,13 +451,16 @@ pub struct Extra<'a> {
pub strict: Option<bool>,
/// context used in validator functions
pub context: Option<&'a PyAny>,
// if we should do exhaustive validation
pub exhaustive: bool,
}

impl<'a> Extra<'a> {
pub fn new(strict: Option<bool>, context: Option<&'a PyAny>) -> Self {
Extra {
strict,
context,
exhaustive: true,
..Default::default()
}
}
Expand All @@ -469,6 +473,16 @@ impl<'a> Extra<'a> {
field: self.field,
strict: Some(true),
context: self.context,
exhaustive: self.exhaustive,
}
}
pub fn with_exhaustiveness(&self, exhaustive: bool) -> Self {
Self {
data: self.data,
field: self.field,
strict: Some(true),
context: self.context,
exhaustive,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/validators/typed_dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ impl Validator for TypedDictValidator {
field: None,
strict: extra.strict,
context: extra.context,
exhaustive: true,
};

macro_rules! process {
Expand Down
13 changes: 12 additions & 1 deletion src/validators/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,17 @@ impl Validator for UnionValidator {
recursion_guard: &'s mut RecursionGuard,
) -> ValResult<'data, PyObject> {
if extra.strict.unwrap_or(self.strict) {
// 1st pass: non exhaustive
let non_exhaustive_extra = extra.with_exhaustiveness(false);
if let Some(res) = self
.choices
.iter()
.map(|validator| validator.validate(py, input, &non_exhaustive_extra, slots, recursion_guard))
.find(ValResult::is_ok)
{
return res;
}

let mut errors: Option<Vec<ValLineError>> = match self.custom_error {
None => Some(Vec::with_capacity(self.choices.len())),
_ => None,
Expand All @@ -110,7 +121,7 @@ impl Validator for UnionValidator {
} else {
// 1st pass: check if the value is an exact instance of one of the Union types,
// e.g. use validate in strict mode
let strict_extra = extra.as_strict();
let strict_extra = extra.as_strict().with_exhaustiveness(false);
if let Some(res) = self
.choices
.iter()
Expand Down
14 changes: 14 additions & 0 deletions tests/benchmarks/test_micro_benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,20 @@ def test_smart_union_core(self, benchmark):

benchmark(v.validate_python, 1)

@pytest.mark.benchmark(group='smart-union')
def test_smart_union_deep(self, benchmark):
v = SchemaValidator(
{
'type': 'union',
'choices': [
{'type': 'list', 'items_schema': {'type': 'str'}},
{'type': 'list', 'items_schema': {'type': 'int'}},
],
}
)
data = [1] * 1_000
benchmark(v.validate_python, data)

@skip_pydantic
@pytest.mark.benchmark(group='smart-union')
def test_smart_union_pyd(self, benchmark):
Expand Down