| 70 | |
| 71 | |
| 72 | def pydantic_encoder(obj: Any) -> Any: |
| 73 | from dataclasses import asdict, is_dataclass |
| 74 | |
| 75 | from pydantic.v1.main import BaseModel |
| 76 | |
| 77 | if isinstance(obj, BaseModel): |
| 78 | return obj.dict() |
| 79 | elif is_dataclass(obj): |
| 80 | return asdict(obj) |
| 81 | |
| 82 | # Check the class type and its superclasses for a matching encoder |
| 83 | for base in obj.__class__.__mro__[:-1]: |
| 84 | try: |
| 85 | encoder = ENCODERS_BY_TYPE[base] |
| 86 | except KeyError: |
| 87 | continue |
| 88 | return encoder(obj) |
| 89 | else: # We have exited the for loop without finding a suitable encoder |
| 90 | raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") |
| 91 | |
| 92 | |
| 93 | def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any: |