File: collection_field.py

package info (click to toggle)
python-marshmallow-dataclass 8.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 332 kB
  • sloc: python: 2,351; makefile: 11; sh: 6
file content (51 lines) | stat: -rw-r--r-- 1,640 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import typing

import marshmallow


class Sequence(marshmallow.fields.List):
    """
    A sequence field, basically an immutable version of the list field.
    """

    def _deserialize(  # type: ignore[override]
        self,
        value: typing.Any,
        attr: typing.Any,
        data: typing.Any,
        **kwargs: typing.Any,
    ) -> typing.Optional[typing.Sequence[typing.Any]]:
        optional_list = super()._deserialize(value, attr, data, **kwargs)
        return None if optional_list is None else tuple(optional_list)


class Set(marshmallow.fields.List):
    """
    A set field. A set is an unordered/mutable collection of unique elements, same for frozenset
    except it's immutable.

    Notes:
        Beware the a Set guarantees uniqueness in the resulting list but in return the item's order
        will be random. So if the order matters, use a List or Sequence !
    """

    def __init__(
        self,
        cls_or_instance: typing.Union[marshmallow.fields.Field, type],
        frozen: bool = False,
        **kwargs,
    ):
        super().__init__(cls_or_instance, **kwargs)
        self.set_type: typing.Type[typing.Union[frozenset, set]] = (
            frozenset if frozen else set
        )

    def _deserialize(  # type: ignore[override]
        self,
        value: typing.Any,
        attr: typing.Any,
        data: typing.Any,
        **kwargs: typing.Any,
    ) -> typing.Union[typing.Set[typing.Any], typing.FrozenSet[typing.Any], None]:
        optional_list = super()._deserialize(value, attr, data, **kwargs)
        return None if optional_list is None else self.set_type(optional_list)