Skip to content

Commit

Permalink
Compare objects MRO with encoders at runtime
Browse files Browse the repository at this point in the history
The previous implementation doesn't handle subclass instances when
pydantic.json.ENCODERS_BY_TYPE is modified after fastapi.encoders import.

This diff makes it easier for developers to add custom encoders that also work
with subclass instances (and it simplifies the code, as well).
  • Loading branch information
ramnes committed Nov 30, 2022
1 parent 83bcdc4 commit cb55292
Showing 1 changed file with 3 additions and 19 deletions.
22 changes: 3 additions & 19 deletions fastapi/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,6 @@
DictIntStrAny = Dict[Union[int, str], Any]


def generate_encoders_by_class_tuples(
type_encoder_map: Dict[Any, Callable[[Any], Any]]
) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(
tuple
)
for type_, encoder in type_encoder_map.items():
encoders_by_class_tuples[encoder] += (type_,)
return encoders_by_class_tuples


encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)


def jsonable_encoder(
obj: Any,
include: Optional[Union[SetIntStr, DictIntStrAny]] = None,
Expand Down Expand Up @@ -142,11 +128,9 @@ def jsonable_encoder(
)
return encoded_list

if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
for base in obj.__class__.__mro__[:-1]:
if base in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[base](obj)

try:
data = dict(obj)
Expand Down

0 comments on commit cb55292

Please sign in to comment.