MCPcopy
hub / github.com/pydantic/pydantic / pydantic_encoder

Function pydantic_encoder

pydantic/v1/json.py:72–90  ·  view source on GitHub ↗
(obj: Any)

Source from the content-addressed store, hash-verified

70
71
72def 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
93def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:

Callers 3

encode_defaultFunction · 0.90
test_deprecated_moduleFunction · 0.90
custom_pydantic_encoderFunction · 0.70

Calls 1

dictMethod · 0.45

Tested by 1

test_deprecated_moduleFunction · 0.72