pydantic / pydantic-core

Core validation logic for pydantic written in rust
MIT License
1.34k stars 207 forks source link

Specify value in UserWarning "serialized value may not be as expected" #1336

Open franklinvp opened 2 weeks ago

franklinvp commented 2 weeks ago

Would it be possible to make this warning more specific by mentioning either the value or perhaps the field that caused it?

I am calling request.model_dump_json(indent=2) and getting

UserWarning: Pydantic serializer warnings:
  Expected `enum` but got `str` - serialized value may not be as expected
  return self.__pydantic_serializer__.to_json(

but there so many enum.Enum in the request that is hard to find which is causing the warning.

The place where the warning message is composed seems[^1] to know the value.

fn fallback_warning(&self, field_type: &str, value: &Bound<'_, PyAny>) {
        if self.mode != WarningsMode::None {
            let type_name = value
                .get_type()
                .qualname()
                .unwrap_or_else(|_| "<unknown python object>".to_owned());
            self.add_warning(format!(
                "Expected `{field_type}` but got `{type_name}` - serialized value may not be as expected"
            ));
        }
    }

[^1]: I am not sure, since I am not familiar with Rust.

franklinvp commented 1 week ago

I think that what #828 is asking (traceback information) has a similar purpose. Although, there it is for serialization errors.

franklinvp commented 1 week ago

By the way, I was able to find the value and field causing the warning by building pydantic-core with the following modification to the error message

-                "Expected `{field_type}` but got `{type_name}` - serialized value may not be as expected"
+                "Expected `{field_type}` but got `{type_name}` value: `{value}` - serialized value may not be as expected"