Custom serializer function for objects, arrays, and other types. Excludes fields with None values unless specified.
(data: Any)
| 116 | } # Set of fields to include even if they have None value |
| 117 | |
| 118 | def serialize(data: Any) -> Union[Dict, List]: |
| 119 | """ |
| 120 | Custom serializer function for objects, arrays, and other types. |
| 121 | Excludes fields with None values unless specified. |
| 122 | """ |
| 123 | if isinstance(data, list) or isinstance(data, tuple): |
| 124 | # Recursively process each element in the list or tuple |
| 125 | return [serialize(item) for item in data] |
| 126 | |
| 127 | if hasattr(data, "__dict__"): |
| 128 | # Otherwise, use the __dict__ method to get attributes |
| 129 | data = data.__dict__ |
| 130 | # Filter out None values, except for specified fields |
| 131 | return { |
| 132 | key: serialize(value) |
| 133 | if isinstance(value, (list, tuple, Dict)) |
| 134 | else value |
| 135 | for key, value in data.items() |
| 136 | if value is not None or key in include_null_fields |
| 137 | } |
| 138 | |
| 139 | return data |
| 140 | |
| 141 | # Serialize the object and then load it back as a dictionary |
| 142 | return json.loads(json.dumps(completion, default=serialize, indent=4)) |
nothing calls this directly
no outgoing calls
no test coverage detected