diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 851fdc3ee..0d46c059b 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -236,9 +236,12 @@ def encode_value( sqlalchemy_safe: bool = True, ) -> Any: if custom_encoder: - if type(obj) in custom_encoder: - return custom_encoder[type(obj)](obj) + # fastpath for exact class match + obj_type = type(obj) + if obj_type in custom_encoder: + return custom_encoder[obj_type](obj) + # fallback to isinstance which uses MRO for encoder_type, encoder_instance in custom_encoder.items(): if isinstance(obj, encoder_type): return encoder_instance(obj)