madman-bob / python-dataclasses-serialization

Serialize/deserialize Python dataclasses to various other data formats
MIT License
25 stars 11 forks source link

Cannot serialize dictionary of type Dict[frozen_dataclass, Any] #12

Closed amijalis closed 4 years ago

amijalis commented 4 years ago

Code to reproduce:

from dataclasses_serialization.bson import BSONSerializer
from dataclasses import dataclass
@dataclass(frozen=True)
class Car:
    name:str

ford = Car(name='ford')
d = {ford: 123}
BSONSerializer.serialize(d)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../python3.9/site-packages/dataclasses_serialization/serializer_base/serializer.py", line 53, in serialize
    return serialization_func(obj)
  File .../python3.9/site-packages/dataclasses_serialization/bson.py", line 57, in <lambda>
    dict: lambda dct: dict_serialization(dct, key_serialization_func=BSONSerializer.serialize, value_serialization_func=BSONSerializer.serialize),
  File ".../python3.9/site-packages/toolz/functoolz.py", line 303, in __call__
    return self._partial(*args, **kwargs)
  File ".../python3.9/site-packages/dataclasses_serialization/serializer_base/dictionary.py", line 50, in dict_serialization
    return {
  File ".../python3.9/site-packages/dataclasses_serialization/serializer_base/dictionary.py", line 51, in <dictcomp>
    key_serialization_func(key): value_serialization_func(value)
TypeError: unhashable type: 'dict'

Thanks for developing this awesome module!

amijalis commented 4 years ago

Thinking about this some more... a JSON or BSON object shouldn't have an object as a key... so this is probably the desired behavior.

madman-bob commented 4 years ago

You're correct that this is desired behaviour.

If you want to use a Car as a key, you need to be explicit about how you want to serialize it.

For example:

BSONSerializer.register_serializer(Car, lambda car: car.name)