Skip to content

Commit 756dd93

Browse files
authored
Merge pull request #60 from pourhouse/bugfix-decimal
Bug fix: add handling of decimal.Decimal value to jsonclass.py
2 parents 3422768 + 34abc58 commit 756dd93

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

jsonrpclib/jsonclass.py

+3
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,9 @@ def dump(
176176
params, attrs = serialize()
177177
return_obj["__jsonclass__"].append(params)
178178
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)])
179182
elif utils.is_enum(obj):
180183
# Add parameters for enumerations
181184
return_obj["__jsonclass__"].append([obj.value])

jsonrpclib/utils.py

+28
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,34 @@ def is_enum(obj): # pylint: disable=unused-argument
121121
return False
122122

123123

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+
124152
# ------------------------------------------------------------------------------
125153
# Common
126154

tests/test_jsonclass.py

+20
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ class Color(enum.Enum):
2828
except ImportError:
2929
enum = None # type: ignore
3030

31+
try:
32+
from decimal import Decimal
33+
except ImportError:
34+
Decimal = None
35+
36+
3137
# JSON-RPC library
3238
from jsonrpclib.jsonclass import dump, load
3339
import jsonrpclib.config
@@ -365,3 +371,17 @@ def test_enum(self):
365371
serialized = dump(data)
366372
result = load(serialized)
367373
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)

0 commit comments

Comments
 (0)