Skip to content

comicbox.formats.base.fields.collection_fields

Marshmallow collection fields.

DictField

Bases: Dict

Dict field for nested schemas with case insensitive keys and sorting.

Source code in comicbox/formats/base/fields/collection_fields.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class DictField(fields.Dict):
    """Dict field for nested schemas with case insensitive keys and sorting."""

    def __init__(
        self,
        *args: Any,
        keys: type[fields.Field] | fields.Field = StringField,
        case_insensitive: bool = True,
        sort: bool = True,
        allow_empty_keys: bool = False,
        allow_empty_values: bool = False,
        **kwargs: Any,
    ) -> None:
        """Set flags."""
        self._case_insensitive = case_insensitive
        self._sort = sort
        self._allow_empty_keys = allow_empty_keys
        self._allow_empty_values = allow_empty_values
        super().__init__(*args, keys=keys, **kwargs)

    @override
    def _deserialize(self, *args: Any, **kwargs: Any) -> dict:
        """Apply flag conditions."""
        result_dict = super()._deserialize(*args, **kwargs)
        result_dict.pop(None, None)
        if not self._allow_empty_keys:
            result_dict.pop("", None)
        if not self._allow_empty_values:
            result_dict = {k: v for k, v in result_dict.items() if not is_empty(v)}
        if self._case_insensitive:
            result_dict = case_insensitive_dict(result_dict)
        return result_dict

    @override
    def _serialize(self, *args: Any, **kwargs: Any) -> dict | None:
        result_dict = super()._serialize(*args, **kwargs)
        if result_dict is None:
            return None
        result_dict.pop(None, None)
        if not self._allow_empty_keys:
            result_dict.pop("", None)
        if not self._allow_empty_values:
            result_dict = {k: v for k, v in result_dict.items() if not is_empty(v)}
        if self._case_insensitive:
            result_dict = case_insensitive_dict(result_dict)
        if self._sort:
            result_dict = dict(sorted(result_dict.items()))
        # Only sort on serialize
        return result_dict

__init__(*args, keys=StringField, case_insensitive=True, sort=True, allow_empty_keys=False, allow_empty_values=False, **kwargs)

Set flags.

Source code in comicbox/formats/base/fields/collection_fields.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def __init__(
    self,
    *args: Any,
    keys: type[fields.Field] | fields.Field = StringField,
    case_insensitive: bool = True,
    sort: bool = True,
    allow_empty_keys: bool = False,
    allow_empty_values: bool = False,
    **kwargs: Any,
) -> None:
    """Set flags."""
    self._case_insensitive = case_insensitive
    self._sort = sort
    self._allow_empty_keys = allow_empty_keys
    self._allow_empty_values = allow_empty_values
    super().__init__(*args, keys=keys, **kwargs)

IntegerListField

Bases: StringListField

A list of integers.

Source code in comicbox/formats/base/fields/collection_fields.py
284
285
286
287
288
289
290
291
class IntegerListField(StringListField):
    """A list of integers."""

    FIELD = IntegerField

    def __init__(self, *args: Any, sort: bool = False, **kwargs: Any) -> None:
        """Use not sorting as the default."""
        super().__init__(*args, sort=sort, **kwargs)

__init__(*args, sort=False, **kwargs)

Use not sorting as the default.

Source code in comicbox/formats/base/fields/collection_fields.py
289
290
291
def __init__(self, *args: Any, sort: bool = False, **kwargs: Any) -> None:
    """Use not sorting as the default."""
    super().__init__(*args, sort=sort, **kwargs)

ListField

Bases: List

List that guarauntees no empty values.

Source code in comicbox/formats/base/fields/collection_fields.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class ListField(fields.List):
    """List that guarauntees no empty values."""

    def __init__(
        self,
        *args: Any,
        # Sorting also does deduplication
        sort: bool = True,
        sort_keys: tuple[str, ...] | list[str] = (),
        allow_empty: bool = False,
        **kwargs: Any,
    ) -> None:
        """Add instance variables."""
        self._sort = sort
        # A tuple of dot delimited keys becomes a tuple of tuples.
        self._sort_keys = tuple(sort_keys)
        self._allow_empty = allow_empty
        super().__init__(*args, **kwargs)

    @override
    def _deserialize(self, value: list[Any] | Any, *args: Any, **kwargs: Any) -> list:
        """Remove empty values."""
        if value is None:
            return []
        values = value if isinstance(value, list) else [value]
        values = super()._deserialize(values, *args, **kwargs)
        if not self._allow_empty:
            values = list(filter_list_empty(values))
        if not values:
            return []
        return values

    @staticmethod
    def get_tag_value(value: Any) -> Any:
        """Override in XmlListField."""
        return value

    def _sort_value(self, value: Any, sort_dict: dict[Any, Any]) -> None:
        if is_empty(value):
            return
        key = []
        if self._sort_keys:
            for key_path in self._sort_keys:
                sort_value = glom(value, key_path, default=None)
                sort_value = self.get_tag_value(sort_value)
                key.append(_comparable(sort_value))
        else:
            key = (_comparable(self.get_tag_value(value)),)
        key = tuple(key)

        # Combine elements that dedupe to the same key. dict.update() returns
        # None, so assigning its result dropped the merged element and left a
        # null in the serialized list. Merge into a new dict instead of
        # mutating in place so the caller's data is never modified.
        old_value = sort_dict.get(key)
        if isinstance(old_value, Mapping) and isinstance(value, Mapping):
            new_value = {**old_value, **value}
        else:
            # Non mappings (and first sightings) can't merge: the later
            # element wins, which is what update() would have done anyway.
            new_value = value

        sort_dict[key] = new_value

    def _sorted(self, values: list[Any]) -> list:
        """Create a dict of ordered keys to deduplicate and sort on."""
        if not self._sort:
            return values

        # If dedupe ever needs to be decoupled, add an index to the key.
        sort_dict = {}
        for value in values:
            self._sort_value(value, sort_dict)
        return [item[1] for item in sorted(sort_dict.items())]

    @override
    def _serialize(self, value: Any, *args: Any, **kwargs: Any) -> list | None:
        if value is None:
            return []
        values = value if isinstance(value, list) else [value]
        values = super()._serialize(values, *args, **kwargs)
        if not values:
            return []
        if not self._allow_empty:
            values = list(filter_list_empty(values))
        if not values:
            return []
        # Only sort on serialize
        return self._sorted(values)

__init__(*args, sort=True, sort_keys=(), allow_empty=False, **kwargs)

Add instance variables.

Source code in comicbox/formats/base/fields/collection_fields.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    *args: Any,
    # Sorting also does deduplication
    sort: bool = True,
    sort_keys: tuple[str, ...] | list[str] = (),
    allow_empty: bool = False,
    **kwargs: Any,
) -> None:
    """Add instance variables."""
    self._sort = sort
    # A tuple of dot delimited keys becomes a tuple of tuples.
    self._sort_keys = tuple(sort_keys)
    self._allow_empty = allow_empty
    super().__init__(*args, **kwargs)

get_tag_value(value) staticmethod

Override in XmlListField.

Source code in comicbox/formats/base/fields/collection_fields.py
87
88
89
90
@staticmethod
def get_tag_value(value: Any) -> Any:
    """Override in XmlListField."""
    return value

StringListField

Bases: List

A list of non empty strings.

Source code in comicbox/formats/base/fields/collection_fields.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class StringListField(fields.List):
    """A list of non empty strings."""

    FIELD: type[fields.Field] = StringField
    DEFAULT_SEPARATORS: str = ",;"
    DEFAULT_SEPARATOR_RE: re.Pattern = re.compile(rf"[{DEFAULT_SEPARATORS}]")

    def __init__(
        self,
        *args: Any,
        as_string: bool = False,
        sort: bool = True,
        separators: str = "",
        **kwargs: Any,
    ) -> None:
        """Initialize as a string list."""
        # The first character in separators is used to join on serialize
        super().__init__(self.FIELD, *args, **kwargs)
        self._as_string = as_string
        self._sort = sort
        if separators:
            re_exp = r"[" + separators + r"]"
            self._split_regex = re.compile(re_exp)
            self._join_separator = separators[0]
        else:
            self._split_regex = self.DEFAULT_SEPARATOR_RE
            self._join_separator = self.DEFAULT_SEPARATORS[0]

    @staticmethod
    def _seq_to_str_seq(seq: Iterable[Any]) -> list[str]:
        return [str(item) for item in seq if not is_empty(item)]

    @override
    def _deserialize(
        self, value: list[str] | set[str] | str, *args: Any, **kwargs: Any
    ) -> list[str | None]:
        """Deserialize CSV encodings of lists."""
        result = []
        if not value:
            return result
        # CSV encoding.
        if isinstance(value, str) and (value := StringField().deserialize(value)):
            value = self._split_regex.split(value)
        if value and is_collection(value):
            # Already deserialized.
            value = self._seq_to_str_seq(value)
            result = super()._deserialize(value, *args, **kwargs)
        return result

    @override
    def _serialize(  # pyright: ignore[reportIncompatibleMethodOverride]  # ty: ignore[incompatible-method-override]
        self, value: set[str], *args: Any, **kwargs: Any
    ) -> list[str | None] | str | None:
        if not value:
            return None
        str_list = self._seq_to_str_seq(value)
        if self._sort:
            # Only sort on serialize
            str_list = sorted(str_list)
        if self._as_string:
            # For subclasses where items aren't always strings
            return self._join_separator.join(str_list)
        return super()._serialize(str_list, *args, **kwargs)

__init__(*args, as_string=False, sort=True, separators='', **kwargs)

Initialize as a string list.

Source code in comicbox/formats/base/fields/collection_fields.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def __init__(
    self,
    *args: Any,
    as_string: bool = False,
    sort: bool = True,
    separators: str = "",
    **kwargs: Any,
) -> None:
    """Initialize as a string list."""
    # The first character in separators is used to join on serialize
    super().__init__(self.FIELD, *args, **kwargs)
    self._as_string = as_string
    self._sort = sort
    if separators:
        re_exp = r"[" + separators + r"]"
        self._split_regex = re.compile(re_exp)
        self._join_separator = separators[0]
    else:
        self._split_regex = self.DEFAULT_SEPARATOR_RE
        self._join_separator = self.DEFAULT_SEPARATORS[0]

StringSetField

Bases: StringListField

A set of non-empty strings.

Source code in comicbox/formats/base/fields/collection_fields.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class StringSetField(StringListField):
    """A set of non-empty strings."""

    @override
    def _deserialize(self, *args: Any, **kwargs: Any) -> set[str | None] | str | None:  # pyright: ignore[reportIncompatibleMethodOverride], # ty: ignore[incompatible-method-override]
        """Cast to a set."""
        str_list = super()._deserialize(*args, **kwargs)
        if not str_list:
            return None
        return set(str_list)

    @override
    def _serialize(
        self, value: set[str], *args: Any, **kwargs: Any
    ) -> list[str | None] | str | None:
        if not value:
            return None
        value = set(value)
        # could force this into a set as well, but may have implications for format serialization
        return super()._serialize(value, *args, **kwargs)

case_insensitive_dict(d)

Make a dict with string keys case insensitive.

Source code in comicbox/formats/base/fields/collection_fields.py
49
50
51
52
def case_insensitive_dict(d: dict) -> dict:
    """Make a dict with string keys case insensitive."""
    cid = {k.lower(): (k, v) for k, v in d.items()}
    return {v[0]: v[1] for v in cid.values()}