| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | """ |
| 8 | Type-safe data interchange for Python data classes. |
| 9 | |
| 10 | :see: https://github.com/hunyadi/strong_typing |
| 11 | """ |
| 12 | |
| 13 | import abc |
| 14 | import base64 |
| 15 | import datetime |
| 16 | import enum |
| 17 | import functools |
| 18 | import inspect |
| 19 | import ipaddress |
| 20 | import sys |
| 21 | import typing |
| 22 | import uuid |
| 23 | from types import FunctionType, MethodType, ModuleType |
| 24 | from typing import ( |
| 25 | Any, |
| 26 | Callable, |
| 27 | Dict, |
| 28 | Generic, |
| 29 | List, |
| 30 | Literal, |
| 31 | NamedTuple, |
| 32 | Optional, |
| 33 | Set, |
| 34 | Tuple, |
| 35 | Type, |
| 36 | TypeVar, |
| 37 | Union, |
| 38 | ) |
| 39 | |
| 40 | from .core import JsonType |
| 41 | from .exception import JsonTypeError, JsonValueError |
| 42 | from .inspection import ( |
| 43 | enum_value_types, |
| 44 | evaluate_type, |
| 45 | get_class_properties, |
| 46 | get_resolved_hints, |
| 47 | is_dataclass_type, |
| 48 | is_named_tuple_type, |
| 49 | is_reserved_property, |
| 50 | is_type_annotated, |
| 51 | is_type_enum, |
| 52 | TypeLike, |
| 53 | unwrap_annotated_type, |
| 54 | ) |
| 55 | from .mapping import python_field_to_json_property |
| 56 | |
| 57 | T = TypeVar("T") |
| 58 | |
| 59 | |
| 60 | class Serializer(abc.ABC, Generic[T]): |
| 61 | @abc.abstractmethod |
| 62 | def generate(self, data: T) -> JsonType: ... |
| 63 | |
| 64 | |
| 65 | class NoneSerializer(Serializer[None]): |
| 66 | def generate(self, data: None) -> None: |
| 67 | # can be directly represented in JSON |
| 68 | return None |
| 69 | |
| 70 | |
| 71 | class BoolSerializer(Serializer[bool]): |
| 72 | def generate(self, data: bool) -> bool: |
| 73 | # can be directly represented in JSON |
| 74 | return data |
| 75 | |
| 76 | |
| 77 | class IntSerializer(Serializer[int]): |
| 78 | def generate(self, data: int) -> int: |
| 79 | # can be directly represented in JSON |
| 80 | return data |
| 81 | |
| 82 | |
| 83 | class FloatSerializer(Serializer[float]): |
| 84 | def generate(self, data: float) -> float: |
| 85 | # can be directly represented in JSON |
| 86 | return data |
| 87 | |
| 88 | |
| 89 | class StringSerializer(Serializer[str]): |
| 90 | def generate(self, data: str) -> str: |
| 91 | # can be directly represented in JSON |
| 92 | return data |
| 93 | |
| 94 | |
| 95 | class BytesSerializer(Serializer[bytes]): |
| 96 | def generate(self, data: bytes) -> str: |
| 97 | return base64.b64encode(data).decode("ascii") |
| 98 | |
| 99 | |
| 100 | class DateTimeSerializer(Serializer[datetime.datetime]): |
| 101 | def generate(self, obj: datetime.datetime) -> str: |
| 102 | if obj.tzinfo is None: |
| 103 | raise JsonValueError( |
| 104 | f"timestamp lacks explicit time zone designator: {obj}" |
| 105 | ) |
| 106 | fmt = obj.isoformat() |
| 107 | if fmt.endswith("+00:00"): |
| 108 | fmt = f"{fmt[:-6]}Z" # Python's isoformat() does not support military time zones like "Zulu" for UTC |
| 109 | return fmt |
| 110 | |
| 111 | |
| 112 | class DateSerializer(Serializer[datetime.date]): |
| 113 | def generate(self, obj: datetime.date) -> str: |
| 114 | return obj.isoformat() |
| 115 | |
| 116 | |
| 117 | class TimeSerializer(Serializer[datetime.time]): |
| 118 | def generate(self, obj: datetime.time) -> str: |
| 119 | return obj.isoformat() |
| 120 | |
| 121 | |
| 122 | class UUIDSerializer(Serializer[uuid.UUID]): |
| 123 | def generate(self, obj: uuid.UUID) -> str: |
| 124 | return str(obj) |
| 125 | |
| 126 | |
| 127 | class IPv4Serializer(Serializer[ipaddress.IPv4Address]): |
| 128 | def generate(self, obj: ipaddress.IPv4Address) -> str: |
| 129 | return str(obj) |
| 130 | |
| 131 | |
| 132 | class IPv6Serializer(Serializer[ipaddress.IPv6Address]): |
| 133 | def generate(self, obj: ipaddress.IPv6Address) -> str: |
| 134 | return str(obj) |
| 135 | |
| 136 | |
| 137 | class EnumSerializer(Serializer[enum.Enum]): |
| 138 | def generate(self, obj: enum.Enum) -> Union[int, str]: |
| 139 | return obj.value |
| 140 | |
| 141 | |
| 142 | class UntypedListSerializer(Serializer[list]): |
| 143 | def generate(self, obj: list) -> List[JsonType]: |
| 144 | return [object_to_json(item) for item in obj] |
| 145 | |
| 146 | |
| 147 | class UntypedDictSerializer(Serializer[dict]): |
| 148 | def generate(self, obj: dict) -> Dict[str, JsonType]: |
| 149 | if obj and isinstance(next(iter(obj.keys())), enum.Enum): |
| 150 | iterator = ( |
| 151 | (key.value, object_to_json(value)) for key, value in obj.items() |
| 152 | ) |
| 153 | else: |
| 154 | iterator = ((str(key), object_to_json(value)) for key, value in obj.items()) |
| 155 | return dict(iterator) |
| 156 | |
| 157 | |
| 158 | class UntypedSetSerializer(Serializer[set]): |
| 159 | def generate(self, obj: set) -> List[JsonType]: |
| 160 | return [object_to_json(item) for item in obj] |
| 161 | |
| 162 | |
| 163 | class UntypedTupleSerializer(Serializer[tuple]): |
| 164 | def generate(self, obj: tuple) -> List[JsonType]: |
| 165 | return [object_to_json(item) for item in obj] |
| 166 | |
| 167 | |
| 168 | class TypedCollectionSerializer(Serializer, Generic[T]): |
| 169 | generator: Serializer[T] |
| 170 | |
| 171 | def __init__(self, item_type: Type[T], context: Optional[ModuleType]) -> None: |
| 172 | self.generator = _get_serializer(item_type, context) |
| 173 | |
| 174 | |
| 175 | class TypedListSerializer(TypedCollectionSerializer[T]): |
| 176 | def generate(self, obj: List[T]) -> List[JsonType]: |
| 177 | return [self.generator.generate(item) for item in obj] |
| 178 | |
| 179 | |
| 180 | class TypedStringDictSerializer(TypedCollectionSerializer[T]): |
| 181 | def __init__(self, value_type: Type[T], context: Optional[ModuleType]) -> None: |
| 182 | super().__init__(value_type, context) |
| 183 | |
| 184 | def generate(self, obj: Dict[str, T]) -> Dict[str, JsonType]: |
| 185 | return {key: self.generator.generate(value) for key, value in obj.items()} |
| 186 | |
| 187 | |
| 188 | class TypedEnumDictSerializer(TypedCollectionSerializer[T]): |
| 189 | def __init__( |
| 190 | self, |
| 191 | key_type: Type[enum.Enum], |
| 192 | value_type: Type[T], |
| 193 | context: Optional[ModuleType], |
| 194 | ) -> None: |
| 195 | super().__init__(value_type, context) |
| 196 | |
| 197 | value_types = enum_value_types(key_type) |
| 198 | if len(value_types) != 1: |
| 199 | raise JsonTypeError( |
| 200 | f"invalid key type, enumerations must have a consistent member value type but several types found: {value_types}" |
| 201 | ) |
| 202 | |
| 203 | value_type = value_types.pop() |
| 204 | if value_type is not str: |
| 205 | raise JsonTypeError( |
| 206 | "invalid enumeration key type, expected `enum.Enum` with string values" |
| 207 | ) |
| 208 | |
| 209 | def generate(self, obj: Dict[enum.Enum, T]) -> Dict[str, JsonType]: |
| 210 | return {key.value: self.generator.generate(value) for key, value in obj.items()} |
| 211 | |
| 212 | |
| 213 | class TypedSetSerializer(TypedCollectionSerializer[T]): |
| 214 | def generate(self, obj: Set[T]) -> JsonType: |
| 215 | return [self.generator.generate(item) for item in obj] |
| 216 | |
| 217 | |
| 218 | class TypedTupleSerializer(Serializer[tuple]): |
| 219 | item_generators: Tuple[Serializer, ...] |
| 220 | |
| 221 | def __init__( |
| 222 | self, item_types: Tuple[type, ...], context: Optional[ModuleType] |
| 223 | ) -> None: |
| 224 | self.item_generators = tuple( |
| 225 | _get_serializer(item_type, context) for item_type in item_types |
| 226 | ) |
| 227 | |
| 228 | def generate(self, obj: tuple) -> List[JsonType]: |
| 229 | return [ |
| 230 | item_generator.generate(item) |
| 231 | for item_generator, item in zip(self.item_generators, obj) |
| 232 | ] |
| 233 | |
| 234 | |
| 235 | class CustomSerializer(Serializer): |
| 236 | converter: Callable[[object], JsonType] |
| 237 | |
| 238 | def __init__(self, converter: Callable[[object], JsonType]) -> None: |
| 239 | self.converter = converter |
| 240 | |
| 241 | def generate(self, obj: object) -> JsonType: |
| 242 | return self.converter(obj) |
| 243 | |
| 244 | |
| 245 | class FieldSerializer(Generic[T]): |
| 246 | """ |
| 247 | Serializes a Python object field into a JSON property. |
| 248 | |
| 249 | :param field_name: The name of the field in a Python class to read data from. |
| 250 | :param property_name: The name of the JSON property to write to a JSON `object`. |
| 251 | :param generator: A compatible serializer that can handle the field's type. |
| 252 | """ |
| 253 | |
| 254 | field_name: str |
| 255 | property_name: str |
| 256 | generator: Serializer |
| 257 | |
| 258 | def __init__( |
| 259 | self, field_name: str, property_name: str, generator: Serializer[T] |
| 260 | ) -> None: |
| 261 | self.field_name = field_name |
| 262 | self.property_name = property_name |
| 263 | self.generator = generator |
| 264 | |
| 265 | def generate_field(self, obj: object, object_dict: Dict[str, JsonType]) -> None: |
| 266 | value = getattr(obj, self.field_name) |
| 267 | if value is not None: |
| 268 | object_dict[self.property_name] = self.generator.generate(value) |
| 269 | |
| 270 | |
| 271 | class TypedClassSerializer(Serializer[T]): |
| 272 | property_generators: List[FieldSerializer] |
| 273 | |
| 274 | def __init__(self, class_type: Type[T], context: Optional[ModuleType]) -> None: |
| 275 | self.property_generators = [ |
| 276 | FieldSerializer( |
| 277 | field_name, |
| 278 | python_field_to_json_property(field_name, field_type), |
| 279 | _get_serializer(field_type, context), |
| 280 | ) |
| 281 | for field_name, field_type in get_class_properties(class_type) |
| 282 | ] |
| 283 | |
| 284 | def generate(self, obj: T) -> Dict[str, JsonType]: |
| 285 | object_dict: Dict[str, JsonType] = {} |
| 286 | for property_generator in self.property_generators: |
| 287 | property_generator.generate_field(obj, object_dict) |
| 288 | |
| 289 | return object_dict |
| 290 | |
| 291 | |
| 292 | class TypedNamedTupleSerializer(TypedClassSerializer[NamedTuple]): |
| 293 | def __init__( |
| 294 | self, class_type: Type[NamedTuple], context: Optional[ModuleType] |
| 295 | ) -> None: |
| 296 | super().__init__(class_type, context) |
| 297 | |
| 298 | |
| 299 | class DataclassSerializer(TypedClassSerializer[T]): |
| 300 | def __init__(self, class_type: Type[T], context: Optional[ModuleType]) -> None: |
| 301 | super().__init__(class_type, context) |
| 302 | |
| 303 | |
| 304 | class UnionSerializer(Serializer): |
| 305 | def generate(self, obj: Any) -> JsonType: |
| 306 | return object_to_json(obj) |
| 307 | |
| 308 | |
| 309 | class LiteralSerializer(Serializer): |
| 310 | generator: Serializer |
| 311 | |
| 312 | def __init__(self, values: Tuple[Any, ...], context: Optional[ModuleType]) -> None: |
| 313 | literal_type_tuple = tuple(type(value) for value in values) |
| 314 | literal_type_set = set(literal_type_tuple) |
| 315 | if len(literal_type_set) != 1: |
| 316 | value_names = ", ".join(repr(value) for value in values) |
| 317 | raise TypeError( |
| 318 | f"type `Literal[{value_names}]` expects consistent literal value types but got: {literal_type_tuple}" |
| 319 | ) |
| 320 | |
| 321 | literal_type = literal_type_set.pop() |
| 322 | self.generator = _get_serializer(literal_type, context) |
| 323 | |
| 324 | def generate(self, obj: Any) -> JsonType: |
| 325 | return self.generator.generate(obj) |
| 326 | |
| 327 | |
| 328 | class UntypedNamedTupleSerializer(Serializer): |
| 329 | fields: Dict[str, str] |
| 330 | |
| 331 | def __init__(self, class_type: Type[NamedTuple]) -> None: |
| 332 | # named tuples are also instances of tuple |
| 333 | self.fields = {} |
| 334 | field_names: Tuple[str, ...] = class_type._fields |
| 335 | for field_name in field_names: |
| 336 | self.fields[field_name] = python_field_to_json_property(field_name) |
| 337 | |
| 338 | def generate(self, obj: NamedTuple) -> JsonType: |
| 339 | object_dict = {} |
| 340 | for field_name, property_name in self.fields.items(): |
| 341 | value = getattr(obj, field_name) |
| 342 | object_dict[property_name] = object_to_json(value) |
| 343 | |
| 344 | return object_dict |
| 345 | |
| 346 | |
| 347 | class UntypedClassSerializer(Serializer): |
| 348 | def generate(self, obj: object) -> JsonType: |
| 349 | # iterate over object attributes to get a standard representation |
| 350 | object_dict = {} |
| 351 | for name in dir(obj): |
| 352 | if is_reserved_property(name): |
| 353 | continue |
| 354 | |
| 355 | value = getattr(obj, name) |
| 356 | if value is None: |
| 357 | continue |
| 358 | |
| 359 | # filter instance methods |
| 360 | if inspect.ismethod(value): |
| 361 | continue |
| 362 | |
| 363 | object_dict[python_field_to_json_property(name)] = object_to_json(value) |
| 364 | |
| 365 | return object_dict |
| 366 | |
| 367 | |
| 368 | def create_serializer( |
| 369 | typ: TypeLike, context: Optional[ModuleType] = None |
| 370 | ) -> Serializer: |
| 371 | """ |
| 372 | Creates a serializer engine to produce an object that can be directly converted into a JSON string. |
| 373 | |
| 374 | When serializing a Python object into a JSON object, the following transformations are applied: |
| 375 | |
| 376 | * Fundamental types (`bool`, `int`, `float` or `str`) are returned as-is. |
| 377 | * Date and time types (`datetime`, `date` or `time`) produce an ISO 8601 format string with time zone |
| 378 | (ending with `Z` for UTC). |
| 379 | * Byte arrays (`bytes`) are written as a string with Base64 encoding. |
| 380 | * UUIDs (`uuid.UUID`) are written as a UUID string as per RFC 4122. |
| 381 | * Enumerations yield their enumeration value. |
| 382 | * Containers (e.g. `list`, `dict`, `set`, `tuple`) are processed recursively. |
| 383 | * Complex objects with properties (including data class types) generate dictionaries of key-value pairs. |
| 384 | |
| 385 | :raises TypeError: A serializer engine cannot be constructed for the input type. |
| 386 | """ |
| 387 | |
| 388 | if context is None: |
| 389 | if isinstance(typ, type): |
| 390 | context = sys.modules[typ.__module__] |
| 391 | |
| 392 | return _get_serializer(typ, context) |
| 393 | |
| 394 | |
| 395 | def _get_serializer(typ: TypeLike, context: Optional[ModuleType]) -> Serializer: |
| 396 | if isinstance(typ, (str, typing.ForwardRef)): |
| 397 | if context is None: |
| 398 | raise TypeError(f"missing context for evaluating type: {typ}") |
| 399 | |
| 400 | typ = evaluate_type(typ, context) |
| 401 | |
| 402 | if isinstance(typ, type): |
| 403 | return _fetch_serializer(typ) |
| 404 | else: |
| 405 | # special forms are not always hashable |
| 406 | return _create_serializer(typ, context) |
| 407 | |
| 408 | |
| 409 | @functools.lru_cache(maxsize=None) |
| 410 | def _fetch_serializer(typ: type) -> Serializer: |
| 411 | context = sys.modules[typ.__module__] |
| 412 | return _create_serializer(typ, context) |
| 413 | |
| 414 | |
| 415 | def _create_serializer(typ: TypeLike, context: Optional[ModuleType]) -> Serializer: |
| 416 | # check for well-known types |
| 417 | if typ is type(None): |
| 418 | return NoneSerializer() |
| 419 | elif typ is bool: |
| 420 | return BoolSerializer() |
| 421 | elif typ is int: |
| 422 | return IntSerializer() |
| 423 | elif typ is float: |
| 424 | return FloatSerializer() |
| 425 | elif typ is str: |
| 426 | return StringSerializer() |
| 427 | elif typ is bytes: |
| 428 | return BytesSerializer() |
| 429 | elif typ is datetime.datetime: |
| 430 | return DateTimeSerializer() |
| 431 | elif typ is datetime.date: |
| 432 | return DateSerializer() |
| 433 | elif typ is datetime.time: |
| 434 | return TimeSerializer() |
| 435 | elif typ is uuid.UUID: |
| 436 | return UUIDSerializer() |
| 437 | elif typ is ipaddress.IPv4Address: |
| 438 | return IPv4Serializer() |
| 439 | elif typ is ipaddress.IPv6Address: |
| 440 | return IPv6Serializer() |
| 441 | |
| 442 | # dynamically-typed collection types |
| 443 | if typ is list: |
| 444 | return UntypedListSerializer() |
| 445 | elif typ is dict: |
| 446 | return UntypedDictSerializer() |
| 447 | elif typ is set: |
| 448 | return UntypedSetSerializer() |
| 449 | elif typ is tuple: |
| 450 | return UntypedTupleSerializer() |
| 451 | |
| 452 | # generic types (e.g. list, dict, set, etc.) |
| 453 | origin_type = typing.get_origin(typ) |
| 454 | if origin_type is list: |
| 455 | (list_item_type,) = typing.get_args(typ) # unpack single tuple element |
| 456 | return TypedListSerializer(list_item_type, context) |
| 457 | elif origin_type is dict: |
| 458 | key_type, value_type = typing.get_args(typ) |
| 459 | if key_type is str: |
| 460 | return TypedStringDictSerializer(value_type, context) |
| 461 | elif issubclass(key_type, enum.Enum): |
| 462 | return TypedEnumDictSerializer(key_type, value_type, context) |
| 463 | elif origin_type is set: |
| 464 | (set_member_type,) = typing.get_args(typ) # unpack single tuple element |
| 465 | return TypedSetSerializer(set_member_type, context) |
| 466 | elif origin_type is tuple: |
| 467 | return TypedTupleSerializer(typing.get_args(typ), context) |
| 468 | elif origin_type is Union: |
| 469 | return UnionSerializer() |
| 470 | elif origin_type is Literal: |
| 471 | return LiteralSerializer(typing.get_args(typ), context) |
| 472 | |
| 473 | if is_type_annotated(typ): |
| 474 | return create_serializer(unwrap_annotated_type(typ)) |
| 475 | |
| 476 | # check if object has custom serialization method |
| 477 | convert_func = getattr(typ, "to_json", None) |
| 478 | if callable(convert_func): |
| 479 | return CustomSerializer(convert_func) |
| 480 | |
| 481 | if is_type_enum(typ): |
| 482 | return EnumSerializer() |
| 483 | if is_dataclass_type(typ): |
| 484 | return DataclassSerializer(typ, context) |
| 485 | if is_named_tuple_type(typ): |
| 486 | if getattr(typ, "__annotations__", None): |
| 487 | return TypedNamedTupleSerializer(typ, context) |
| 488 | else: |
| 489 | return UntypedNamedTupleSerializer(typ) |
| 490 | |
| 491 | # fail early if caller passes an object with an exotic type |
| 492 | if ( |
| 493 | not isinstance(typ, type) |
| 494 | or typ is FunctionType |
| 495 | or typ is MethodType |
| 496 | or typ is type |
| 497 | or typ is ModuleType |
| 498 | ): |
| 499 | raise TypeError(f"object of type {typ} cannot be represented in JSON") |
| 500 | |
| 501 | if get_resolved_hints(typ): |
| 502 | return TypedClassSerializer(typ, context) |
| 503 | else: |
| 504 | return UntypedClassSerializer() |
| 505 | |
| 506 | |
| 507 | def object_to_json(obj: Any) -> JsonType: |
| 508 | """ |
| 509 | Converts a Python object to a representation that can be exported to JSON. |
| 510 | |
| 511 | * Fundamental types (e.g. numeric types) are written as is. |
| 512 | * Date and time types are serialized in the ISO 8601 format with time zone. |
| 513 | * A byte array is written as a string with Base64 encoding. |
| 514 | * UUIDs are written as a UUID string. |
| 515 | * Enumerations are written as their value. |
| 516 | * Containers (e.g. `list`, `dict`, `set`, `tuple`) are exported recursively. |
| 517 | * Objects with properties (including data class types) are converted to a dictionaries of key-value pairs. |
| 518 | """ |
| 519 | |
| 520 | typ: type = type(obj) |
| 521 | generator = create_serializer(typ) |
| 522 | return generator.generate(obj) |