@@ -180,8 +180,8 @@ impl Validator for ModelFieldsValidator {
180180 self . validate_by_get_item ( py, input, dict, state) ?
181181 } ;
182182
183- // if we have extra=allow, but we didn't create a dict because we were validating
184- // from attributes, set it now so __pydantic_extra__ is always a dict if extra=allow
183+ // if we have extra=allow, but we didn't create a dict (e.g. because we were validating
184+ // from attributes or there were no extra keys) , set it now so __pydantic_extra__ is always a dict if extra=allow
185185 if matches ! ( extra_behavior, ExtraBehavior :: Allow ) && model_extra_dict_op. is_none ( ) {
186186 model_extra_dict_op = Some ( PyDict :: new ( py) ) ;
187187 }
@@ -564,7 +564,6 @@ impl ModelFieldsValidator {
564564 let state = & mut state. scoped_set_data ( Some ( model_dict. clone ( ) ) ) ;
565565 let state = & mut state. scoped_clear_field_error ( ) ;
566566
567- let model_extra_dict = PyDict :: new ( py) ;
568567 for ( key, value) in & * * json_object {
569568 let mut handled = false ;
570569 let key = key. as_ref ( ) ;
@@ -604,6 +603,7 @@ impl ModelFieldsValidator {
604603 }
605604 ExtraBehavior :: Ignore => { }
606605 ExtraBehavior :: Allow => {
606+ let model_extra_dict = model_extra_dict_op. get_or_insert_with ( || PyDict :: new ( py) ) ;
607607 let py_key: Bound < ' _ , PyString > = new_py_string ( py, key, state. cache_str ( ) ) ;
608608 if let Some ( validator) = & self . extras_validator {
609609 match validator. validate ( py, value, state) {
@@ -690,10 +690,6 @@ impl ModelFieldsValidator {
690690 model_dict. set_item ( & field. name , field_value) ?;
691691 }
692692
693- if matches ! ( extra_behavior, ExtraBehavior :: Allow ) {
694- model_extra_dict_op = Some ( model_extra_dict) ;
695- }
696-
697693 if !errors. is_empty ( ) {
698694 return Err ( ValError :: LineErrors ( errors) ) ;
699695 }
0 commit comments