marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Implement a field.Set?

Open mikegrima opened this issue 4 years ago • 3 comments

I was curious why Marshmallow didn't have a field.Set for Python sets.

I would imagine the code would be mirror identical to List (https://github.com/marshmallow-code/marshmallow/blob/dev/src/marshmallow/fields.py#L656) only with a list being serialized into a set, and deserialized back into a list.

Would this be easy to implement? Any pitfalls I should be made aware of?

mikegrima avatar Mar 25 '20 01:03 mikegrima

I'm not opposed to adding a Set field, though we should probably do something along the lines of what @deckar01 has proposed here: https://github.com/marshmallow-code/marshmallow/issues/1263#issuecomment-503755620 . That would make it easier to implement any custom iterable field in userland.

sloria avatar Mar 25 '20 02:03 sloria

We generally have fields matching the deserialized type, with parameters to customize the serialized form.

I guess there has not been much incentive to serialize lists as sets because

  • you lose the order, so it does not round-trip
  • users often serialize as json, which means lists become arrays

Unless you meant the opposite.

A Set field could indeed be added. It would serialize as list and deserialize as set.

It could be based on an Iterable base field. See #1263.

lafrech avatar Mar 29 '21 07:03 lafrech

@lafrech It would be de-serializing from JSON. The implementation would be similar to Pydantic's.

mikegrima avatar Mar 29 '21 20:03 mikegrima