File tree 3 files changed +51
-0
lines changed
3 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -176,6 +176,9 @@ def dump(
176
176
params , attrs = serialize ()
177
177
return_obj ["__jsonclass__" ].append (params )
178
178
return_obj .update (attrs )
179
+ elif utils .is_decimal (obj ):
180
+ # Add parameter for Decimal that works with JSON
181
+ return_obj ["__jsonclass__" ].append ([str (obj )])
179
182
elif utils .is_enum (obj ):
180
183
# Add parameters for enumerations
181
184
return_obj ["__jsonclass__" ].append ([obj .value ])
Original file line number Diff line number Diff line change @@ -121,6 +121,34 @@ def is_enum(obj): # pylint: disable=unused-argument
121
121
return False
122
122
123
123
124
+ # ------------------------------------------------------------------------------
125
+ # Decimal
126
+
127
+ try :
128
+ import decimal
129
+
130
+ def is_decimal (obj ):
131
+ """
132
+ Checks if an object is a decimal.Decimal
133
+
134
+ :param obj: Object to test
135
+ :return: True if the object is a Decimal
136
+ """
137
+ return isinstance (obj , decimal .Decimal )
138
+
139
+
140
+ except ImportError :
141
+ # Decimal introduced in Python 2.4
142
+ def is_decimal (obj ): # pylint: disable=unused-argument
143
+ """
144
+ Before Python 2.4, Decimal did not exist.
145
+
146
+ :param obj: Object to test
147
+ :return: Always False
148
+ """
149
+ return False
150
+
151
+
124
152
# ------------------------------------------------------------------------------
125
153
# Common
126
154
Original file line number Diff line number Diff line change @@ -28,6 +28,12 @@ class Color(enum.Enum):
28
28
except ImportError :
29
29
enum = None # type: ignore
30
30
31
+ try :
32
+ from decimal import Decimal
33
+ except ImportError :
34
+ Decimal = None
35
+
36
+
31
37
# JSON-RPC library
32
38
from jsonrpclib .jsonclass import dump , load
33
39
import jsonrpclib .config
@@ -365,3 +371,17 @@ def test_enum(self):
365
371
serialized = dump (data )
366
372
result = load (serialized )
367
373
self .assertListEqual (data , result )
374
+
375
+ def test_decimal (self ):
376
+ """
377
+ Tests the serialization of decimal.Decimal
378
+ """
379
+ if Decimal is None :
380
+ self .skipTest ("decimal package not available." )
381
+
382
+ for d in (1.1 , "3.2" ):
383
+ d_dec = Decimal (d )
384
+ serialized = dump (d_dec )
385
+ result = load (serialized )
386
+ self .assertIsInstance (result , Decimal )
387
+ self .assertEqual (result , d_dec )
You can’t perform that action at this time.
0 commit comments