mirror of
https://github.com/fmtr/haco.git
synced 2026-10-26 19:01:51 -04:00
38 lines
965 B
Python
38 lines
965 B
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, fields
|
|
from typing import Any
|
|
|
|
|
|
@dataclass(kw_only=True)
|
|
class Base:
|
|
"""
|
|
|
|
Base class for haco objects. Provides model dumping functionality.
|
|
|
|
"""
|
|
|
|
DATA = dict()
|
|
|
|
def model_dump(self) -> dict[str, Any]:
|
|
"""
|
|
|
|
Dump the object to a dictionary, excluding fields marked with `exclude=True` in metadata.
|
|
|
|
"""
|
|
data = {} | self.DATA
|
|
for fld in fields(self):
|
|
meta = fld.metadata
|
|
if meta.get('exclude', False):
|
|
continue
|
|
|
|
value = getattr(self, fld.name)
|
|
|
|
if hasattr(value, self.model_dump.__name__):
|
|
value = value.model_dump()
|
|
elif isinstance(value, list):
|
|
value = [v.model_dump() if hasattr(v, self.model_dump.__name__) else v for v in value]
|
|
|
|
if value is not None:
|
|
data[fld.name] = value
|
|
return data
|