Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e6f14d5

Browse files
committed
re-cast int/float subclasses to int/float in json_clean
Protects against custom `__str__` in int subclasses (e.g. enums). Works around a [bug in the stdlib](http://bugs.python.org/issue12657). closes #4598
1 parent c73b412 commit e6f14d5

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

IPython/utils/jsonutil.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,8 @@ def json_clean(obj):
194194
>>> json_clean(True)
195195
True
196196
"""
197-
# types that are 'atomic' and ok in json as-is. bool doesn't need to be
198-
# listed explicitly because bools pass as int instances
199-
atomic_ok = (unicode_type, int, type(None))
197+
# types that are 'atomic' and ok in json as-is.
198+
atomic_ok = (unicode_type, type(None))
200199

201200
# containers that we need to convert into lists
202201
container_to_list = (tuple, set, types.GeneratorType)
@@ -205,7 +204,14 @@ def json_clean(obj):
205204
# cast out-of-range floats to their reprs
206205
if math.isnan(obj) or math.isinf(obj):
207206
return repr(obj)
208-
return obj
207+
return float(obj)
208+
209+
if isinstance(obj, int):
210+
# cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598)
211+
if isinstance(obj, bool):
212+
# bools are ints, but we don't want to cast them to 0,1
213+
return obj
214+
return int(obj)
209215

210216
if isinstance(obj, atomic_ok):
211217
return obj

0 commit comments

Comments
 (0)