From a70897a467aab07929d0aaa9dd34cc89e708668f 2014-07-07 04:53:31 From: MinRK Date: 2014-07-07 04:53:31 Subject: [PATCH] Backport PR #6081: don’t modify dict keys while iterating through them in `jsonutil.rekey`, which could prevent some keys from being modified during the iteration. closes #5901 Fixes 'unorderable types' failure on Python 3 in test_client: ... --- diff --git a/IPython/utils/jsonutil.py b/IPython/utils/jsonutil.py index f618550..b41a422 100644 --- a/IPython/utils/jsonutil.py +++ b/IPython/utils/jsonutil.py @@ -39,22 +39,18 @@ datetime.strptime("1", "%d") def rekey(dikt): """Rekey a dict that has been forced to use str keys where there should be ints by json.""" - for k in dikt: + for k in list(dikt): if isinstance(k, string_types): - ik=fk=None + nk = None try: - ik = int(k) + nk = int(k) except ValueError: try: - fk = float(k) + nk = float(k) except ValueError: continue - if ik is not None: - nk = ik - else: - nk = fk if nk in dikt: - raise KeyError("already have key %r"%nk) + raise KeyError("already have key %r" % nk) dikt[nk] = dikt.pop(k) return dikt diff --git a/IPython/utils/tests/test_jsonutil.py b/IPython/utils/tests/test_jsonutil.py index 6c84778..0d55178 100644 --- a/IPython/utils/tests/test_jsonutil.py +++ b/IPython/utils/tests/test_jsonutil.py @@ -53,6 +53,13 @@ def test(): json.loads(json.dumps(out)) +def test_rekey(): + # This could fail due to modifying the dict keys in-place on Python 3 + d = { i:i for i in map(str, range(128)) } + d = jsonutil.rekey(d) + for key in d: + nt.assert_is_instance(key, int) + def test_encode_images(): # invalid data, but the header and footer are from real files