55from collections import defaultdict , deque
66from decimal import Decimal
77from enum import Enum
8- from pathlib import Path , PurePath
8+ from pathlib import PurePath
99from re import Pattern
1010from types import GeneratorType
1111from typing import TYPE_CHECKING , Any
@@ -103,17 +103,14 @@ def jsonable_encoder( # noqa: PLR0911
103103 custom_serializer = custom_serializer ,
104104 )
105105
106- # Enums
107- if isinstance (obj , Enum ):
108- return obj .value
106+ # Simple type dispatch (exact type match, then isinstance for subclasses)
107+ encoder = ENCODERS_BY_TYPE .get (type (obj ))
108+ if encoder is not None :
109+ return encoder (obj )
109110
110- # Paths
111- if isinstance (obj , PurePath ):
112- return str (obj )
113-
114- # Scalars
115- if isinstance (obj , (str , int , float , type (None ))):
116- return obj
111+ for encoder_fn , classes_tuple in _encoders_by_class_tuples .items ():
112+ if isinstance (obj , classes_tuple ):
113+ return encoder_fn (obj )
117114
118115 # Dictionaries
119116 if isinstance (obj , dict ):
@@ -140,14 +137,6 @@ def jsonable_encoder( # noqa: PLR0911
140137 custom_serializer = custom_serializer ,
141138 )
142139
143- # Other types
144- if type (obj ) in ENCODERS_BY_TYPE :
145- return ENCODERS_BY_TYPE [type (obj )](obj )
146-
147- for encoder , classes_tuple in encoders_by_class_tuples .items ():
148- if isinstance (obj , classes_tuple ):
149- return encoder (obj )
150-
151140 # Use custom serializer if present
152141 if custom_serializer :
153142 return custom_serializer (obj )
@@ -346,21 +335,22 @@ def decimal_encoder(dec_value: Decimal) -> int | float:
346335
347336# Encoders for types that are not JSON serializable
348337ENCODERS_BY_TYPE : dict [type [Any ], Callable [[Any ], Any ]] = {
338+ bool : lambda o : o ,
339+ int : lambda o : o ,
340+ float : lambda o : o ,
341+ str : lambda o : o ,
342+ type (None ): lambda o : o ,
349343 bytes : lambda o : o .decode (),
350344 datetime .date : iso_format ,
351345 datetime .datetime : iso_format ,
352346 datetime .time : iso_format ,
353347 datetime .timedelta : lambda td : td .total_seconds (),
354348 Decimal : decimal_encoder ,
355349 Enum : lambda o : o .value ,
356- frozenset : list ,
357- deque : list ,
358- GeneratorType : list ,
359- Path : str ,
350+ PurePath : str ,
360351 Pattern : lambda o : o .pattern ,
361352 SecretBytes : str ,
362353 SecretStr : str ,
363- set : list ,
364354 UUID : str ,
365355}
366356
@@ -376,4 +366,4 @@ def generate_encoders_by_class_tuples(
376366
377367
378368# Mapping of encoders to a tuple of classes that they can encode
379- encoders_by_class_tuples = generate_encoders_by_class_tuples (ENCODERS_BY_TYPE )
369+ _encoders_by_class_tuples = generate_encoders_by_class_tuples (ENCODERS_BY_TYPE )
0 commit comments