Skip to content

Commit 3796409

Browse files
authored
Make __pydantic_extra__ = None when extra='forbid' (#725)
1 parent 0d12efd commit 3796409

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/validators/model_fields.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,9 @@ impl Validator for ModelFieldsValidator {
263263
}
264264
}
265265
}
266-
model_extra_dict_op = Some(model_extra_dict);
266+
if matches!(self.extra_behavior, ExtraBehavior::Allow) {
267+
model_extra_dict_op = Some(model_extra_dict);
268+
}
267269
}
268270
}};
269271
}
@@ -279,9 +281,9 @@ impl Validator for ModelFieldsValidator {
279281
} else {
280282
let fields_set = PySet::new(py, &fields_set_vec)?;
281283

282-
// if we have extra=allow, but we didn't create a dict because we were validate attributes, set it now
283-
// so __pydantic_extra__ is always a dict if extra=allow
284-
if model_extra_dict_op.is_none() && matches!(self.extra_behavior, ExtraBehavior::Allow) {
284+
// if we have extra=allow, but we didn't create a dict because we were validating
285+
// from attributes, set it now so __pydantic_extra__ is always a dict if extra=allow
286+
if matches!(self.extra_behavior, ExtraBehavior::Allow) && model_extra_dict_op.is_none() {
285287
model_extra_dict_op = Some(PyDict::new(py));
286288
};
287289

tests/validators/test_model_fields.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1445,7 +1445,7 @@ def test_alias_extra_forbid(py_and_json: PyAndJson):
14451445
'fields': {'field_a': {'type': 'model-field', 'validation_alias': 'FieldA', 'schema': {'type': 'int'}}},
14461446
}
14471447
)
1448-
assert v.validate_test({'FieldA': 1}) == ({'field_a': 1}, {}, {'field_a'})
1448+
assert v.validate_test({'FieldA': 1}) == ({'field_a': 1}, None, {'field_a'})
14491449

14501450

14511451
def test_with_default_factory():

0 commit comments

Comments
 (0)