27 lines
1.2 KiB
Python
27 lines
1.2 KiB
Python
import logging
|
|
from typing import Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def serialize_context_recursively(context: Any, _path: str = "root") -> Any:
|
|
"""
|
|
Recursively traverses a data structure (dict, list) and converts any object
|
|
with a to_dict() method into its dictionary representation.
|
|
Includes logging to trace the serialization process.
|
|
"""
|
|
if hasattr(context, 'to_dict') and callable(context.to_dict):
|
|
logger.debug(f"Serializing object of type {type(context).__name__} at path: {_path}")
|
|
# If the object itself is serializable, serialize it and then process its dict representation
|
|
return serialize_context_recursively(context.to_dict(), _path)
|
|
|
|
if isinstance(context, dict):
|
|
logger.debug(f"Serializing dict at path: {_path}")
|
|
return {k: serialize_context_recursively(v, f"{_path}.{k}") for k, v in context.items()}
|
|
|
|
if isinstance(context, list):
|
|
logger.debug(f"Serializing list at path: {_path}")
|
|
return [serialize_context_recursively(i, f"{_path}[{idx}]") for idx, i in enumerate(context)]
|
|
|
|
logger.debug(f"Returning primitive at path: {_path}, type: {type(context).__name__}")
|
|
# Return primitives and other JSON-serializable types as-is
|
|
return context |