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

Function pydantic_encoder

pydantic/deprecated/json.py:86–109  ·  view source on GitHub ↗
(obj: Any)

Source from the content-addressed store, hash-verified

84 category=None,
85)
86def pydantic_encoder(obj: Any) -> Any:
87 warnings.warn(
88 '`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
89 category=PydanticDeprecatedSince20,
90 stacklevel=2,
91 )
92 from dataclasses import asdict, is_dataclass
93
94 BaseModel = import_cached_base_model()
95
96 if isinstance(obj, BaseModel):
97 return obj.model_dump()
98 elif is_dataclass(obj):
99 return asdict(obj) # type: ignore
100
101 # Check the class type and its superclasses for a matching encoder
102 for base in obj.__class__.__mro__[:-1]:
103 try:
104 encoder = ENCODERS_BY_TYPE[base]
105 except KeyError:
106 continue
107 return encoder(obj)
108 else: # We have exited the for loop without finding a suitable encoder
109 raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
110
111
112# TODO: Add a suggested migration path once there is a way to use custom encoders

Callers 1

custom_pydantic_encoderFunction · 0.70

Calls 2

import_cached_base_modelFunction · 0.85
model_dumpMethod · 0.45

Tested by

no test coverage detected