Default value from schema does not appear in produced data class
Hello
test.xsd:
<xs:schema xmlns:ns="http://www.test.org" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.test.org/" elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="property1" type="xs:boolean" default="false"/>
<xs:element name="property2" type="xs:boolean" minOccurs="0" default="false"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
xsdata generate test.xsd
I got:
from dataclasses import dataclass, field
from typing import Optional
__NAMESPACE__ = "http://www.test.org/"
@dataclass
class Root:
class Meta:
name = "root"
namespace = "http://www.test.org/"
property1: bool = field(
default=True,
metadata={
"type": "Element",
"required": True,
},
)
property2: Optional[bool] = field(
default=None,
metadata={
"type": "Element",
},
)
The default value for property1 is present in the generated code but value for property2 has been replace by None.
This is done https://github.com/tefra/xsdata/blob/113322b57c2b6f53db2c911fed6ebd1ae40923b8/xsdata/codegen/handlers/sanitize_attributes_default_value.py#L51-L53
I understand that we have incompatible concept, on one hand we have schema that can specify both an optional element and a default value and on an other hand we have https://peps.python.org/pep-0557/ which define field and default value, which is probably why currently the tool remove data previously read from schema.
For my application I would like to be able to retrieve the default value specified in the schema. The business logic will handle it, so I don't want to rely on defaulting mechanism from dataclasses. On the provided example, I would like to produce from a custom plugin where I can customize the rending following code :
@dataclass
class Root:
class Meta:
name = "root"
namespace = "http://www.test.org/"
property1: bool = field(
metadata={
"type": "Element",
"required": True,
"default": True,
}
)
property2: bool = field(
metadata={
"type": "Element",
"default": False,
}
)
The field default attribute is not anymore produce and the default value is produced in metadata dict.
Would you accept patch on sanitize_attributes_default_value.py to avoid losing default attribute value ?
Also I don't understand:
attr.fixed = False