cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Need ability to unstructure convert set to list

Open jacobg opened this issue 5 years ago • 7 comments

  • 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?

jacobg avatar Aug 18 '20 15:08 jacobg

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

jacobg avatar Aug 18 '20 16:08 jacobg

#22 related

jacobg avatar Aug 18 '20 16:08 jacobg

Can you register an unstructure hook for sets and just unstructure the attribute as a list?

Tinche avatar Aug 18 '20 17:08 Tinche

@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

jacobg avatar Aug 18 '20 17:08 jacobg