From f6b310ee816ac523b2bee55c3d79a023b0e8137c Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 2 Apr 2025 10:49:58 +0100 Subject: [PATCH] make anything not acceptable to JSON as a key a compound key --- autoconf/dictable.py | 5 ++++- test_autoconf/test_dictable.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/autoconf/dictable.py b/autoconf/dictable.py index 4185eb7..b91bc37 100644 --- a/autoconf/dictable.py +++ b/autoconf/dictable.py @@ -116,7 +116,10 @@ def to_dict(obj, filter_args: Tuple[str, ...] = ()) -> dict: if isinstance(obj, tuple): return {"type": "tuple", "values": list(map(to_dict, obj))} if isinstance(obj, dict): - if any(isinstance(key, (list, dict, tuple)) for key in obj.keys()): + if any( + not (isinstance(key, (str, int, float, bool)) or key is None) + for key in obj.keys() + ): return compound_key_dict(obj) return { diff --git a/test_autoconf/test_dictable.py b/test_autoconf/test_dictable.py index 5395542..da2c407 100644 --- a/test_autoconf/test_dictable.py +++ b/test_autoconf/test_dictable.py @@ -199,3 +199,16 @@ def test_compound_key(): string = json.dumps(to_dict(d)) assert d == from_dict(json.loads(string)) + + +class Prior: + def __eq__(self, other): + return isinstance(other, Prior) + + def __hash__(self): + return hash(Prior) + + +def test_prior_key(): + string = json.dumps(to_dict({Prior(): 1})) + assert from_dict(json.loads(string)) == {Prior(): 1}