cattrs
cattrs copied to clipboard
Need ability to unstructure convert set to list
- cattrs version: latest
- Python version: 3.7
- Operating System: mac os
Description
When the attr.s class contains a set attribute, the structure conversion leaves it as a set. This is the documented behavior, as described here: https://cattrs.readthedocs.io/en/latest/structuring.html#sets-and-frozensets
The problem is that after calling unstructure, json.dumps(d) is not able to render json from it. Yes, we could write a custom json encoder to handle sets, but it would be great to rely on unstructure to encode it into a canonical dictionary format that can be serialized directly to json without any other conversions. For example, the animal-case library can convert snake cased dictionary key names to camel case, but when its dictionary walker encounters a set, it can't handle it.
Can an option be added to convert to list, or perhaps the ability to override the default set conversion using a register_unstructure_hook?
The attrs library itself seems to have a similar option when calling attr.asdict: retain_collection_types
https://www.attrs.org/en/stable/api.html#attr.asdict
#22 related
Can you register an unstructure hook for sets and just unstructure the attribute as a list?
@Tinche Thanks, I ended up doing that. I initially though that approach wouldn't work, because it wasn't converting sets of custom types that themselves have a registered converter (e.g., a date). But then I saw that's a separate issue: #48