Closed ajoino closed 5 months ago
As is often the case, this is probably PEBCAK: I think this happens because I forgot to set to_xml(skip_empty=True)
. So while this isn't a bug, the library could perhaps be improved by automatically skipping Optional[etree._Element]
fields whose value is None
. That behaviour makes a bit more sense to me than the current one, but I'll leave @dapper91 to decide on that. I might try to implement this though but I'll hold the PR.
A quick test suggests this patch works
--- a/pydantic_xml/serializers/factories/raw.py
+++ b/pydantic_xml/serializers/factories/raw.py
@@ -32,7 +32,7 @@ class ElementSerializer(Serializer):
def serialize(
self, element: XmlElementWriter, value: Any, encoded: Any, *, skip_empty: bool = False,
) -> Optional[XmlElementWriter]:
- if value is None and skip_empty:
+ if value is None:
return element
sub_element = element.from_native(value)
No tests break, but I'm not sure if removing that check has unintended consequences. I don't think it does, but I'm not sure.
@ajoino Hi,
Yes, that's a bug.
This class
can be constructed with zero arguments but fails to serialize
Maybe this is intended behavior, but it feels like a bug to me since every other field can be optional, so raw elements should probably be too.
EDIT:
I also tried adding
nillable=True
to the element but it still doesn't let me construct an instance directly:If I explicitly set
OptionalRaw(optional_raw_element=None).to_xml()
I get the same message as before and if I leave it empty I getOne of the two should work here IMO.