Skip to content

Commit 895d1a4

Browse files
committed
Fix parsing CBOR of dicts
1 parent 90595d3 commit 895d1a4

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

pycardano/serialization.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@
3737
]
3838

3939

40+
def identity(x):
41+
return x
42+
43+
4044
class IndefiniteList(UserList):
4145
def __init__(self, li: Primitive): # type: ignore
4246
super().__init__(li) # type: ignore
@@ -415,6 +419,25 @@ def _restore_dataclass_field(
415419
return f.type.from_primitive(v)
416420
elif isclass(f.type) and issubclass(f.type, IndefiniteList):
417421
return IndefiniteList(v)
422+
elif hasattr(f.type, "__origin__") and (f.type.__origin__ is dict):
423+
t_args = f.type.__args__
424+
if len(t_args) != 2:
425+
raise DeserializeException(
426+
f"Dict types need exactly two type arguments, but got {t_args}"
427+
)
428+
key_t = t_args[0]
429+
val_t = t_args[1]
430+
if isclass(key_t) and issubclass(key_t, CBORSerializable):
431+
key_converter = key_t.from_primitive
432+
else:
433+
key_converter = identity
434+
if isclass(val_t) and issubclass(val_t, CBORSerializable):
435+
val_converter = val_t.from_primitive
436+
else:
437+
val_converter = identity
438+
if not isinstance(v, dict):
439+
raise DeserializeException(f"Expected dict type but got {type(v)}")
440+
return {key_converter(key): val_converter(val) for key, val in v.items()}
418441
elif hasattr(f.type, "__origin__") and (
419442
f.type.__origin__ is Union or f.type.__origin__ is Optional
420443
):

test/pycardano/test_plutus.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ def test_plutus_data_json_dict():
117117
assert test == DictTest.from_json(encoded_json)
118118

119119

120-
@unittest.skip("Plutus tags not supported for cbor entirely right now")
121120
def test_plutus_data_cbor_dict():
122121
test = DictTest({0: LargestTest(), 1: LargestTest()})
123122

0 commit comments

Comments
 (0)