A Python library providing common base classes and utilities for building Pydantic-based models with XML serialization support. This package serves as the foundation for the pydantify project, enabling seamless conversion between Pydantic models and XML representations.
- Base Model Classes:
PydantifyModelandXMLPydantifyModelfor creating structured data models - XML Serialization: Convert Pydantic models to XML with namespace support
- NETCONF Compatibility: Built-in support for NETCONF data root elements
- Type Safety: Full type hints and Pydantic v2 support
- Flexible Output: Pretty-print and custom root element options
pip install pydantify-common- Python >= 3.10
- pydantic >= 2
- lxml >= 6.0.2
Make sure the pydantic model inherits from XMLPydantifyModel and defines namespace and prefix as class variables.
from pydantify_common.model import XMLPydantifyModel
class MyModel(XMLPydantifyModel):
namespace = "http://example.com/schema"
prefix = "ex"
name: str
value: intfrom pydantify_common.helper import model_dump_xml_string
model = MyModel(name="test", value=42)
xml_str = model_dump_xml_string(model, pretty_print=True)
print(xml_str)# Add NETCONF-compatible data root element
xml_str = model_dump_xml_string(model, pretty_print=True, data_root=True)Base class for all pydantify models. Inherits from Pydantic's BaseModel.
class PydantifyModel(BaseModel):
passExtended base class with XML serialization capabilities.
Class Variables:
namespace(str): XML namespace URIprefix(str): XML namespace prefix
Methods:
model_dump_xml() -> Element: Returns an lxml Element representationfields_to_elements(container_name: str | None = None) -> Element: Converts model fields to XML elements
Helper function to serialize XMLPydantifyModel instances to XML strings.
def model_dump_xml_string(
model: XMLPydantifyModel,
*,
pretty_print: bool = False,
data_root: bool = False
) -> strParameters:
model: The XMLPydantifyModel instance to serializepretty_print: Enable formatted XML output (default: False)data_root: Add NETCONF-compatible<data>root element (default: False)
Returns: XML string representation of the model
The project includes comprehensive examples in the tests/examples/ directory:
- with_augment: Demonstrates augmented YANG models with namespace support
- with_import_uses: Shows handling of YANG imports and type reuse
Run tests to see examples in action:
uv run pytest tests/test_examples.py -vvvuv syncmake tests# Type checking
make mypy
# Linting and formatting
make ruffContributions are welcome! Please ensure all tests pass and code follows the project's style guidelines before submitting a pull request.