Skip to content

comicbox.formats.base.fields.enum_fields

Marshmallow Enum Fields.

AgeRatingField

Bases: PrettifiedStringField

Prettified Age Rating.

Source code in comicbox/formats/base/fields/enum_fields.py
271
272
273
274
class AgeRatingField(PrettifiedStringField):
    """Prettified Age Rating."""

    ENUM_ALIAS_MAP = AGE_RATING_ENUM_MAP

ComicInfoMangaEnum

Bases: Enum

Manga enum for ComicInfo.

Source code in comicbox/formats/base/fields/enum_fields.py
184
185
186
187
188
189
190
class ComicInfoMangaEnum(Enum):
    """Manga enum for ComicInfo."""

    UNKNOWN = "Unknown"
    YES = "Yes"
    YES_RTL = "YesAndRightToLeft"
    NO = "No"

ComicInfoMangaField

Bases: EnumBooleanField

Manga field from ComicInfo.

Keeps ComicInfo’s compound vocabulary, YesAndRightToLeft included. The ComicInfo transform splits that value across comicbox’s manga and reading_direction fields and recomposes it on write.

Source code in comicbox/formats/base/fields/enum_fields.py
193
194
195
196
197
198
199
200
201
202
class ComicInfoMangaField(EnumBooleanField):
    """
    Manga field from ComicInfo.

    Keeps ComicInfo's compound vocabulary, YesAndRightToLeft included. The
    ComicInfo transform splits that value across comicbox's manga and
    reading_direction fields and recomposes it on write.
    """

    ENUM = ComicInfoMangaEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]

EnumBooleanField

Bases: EnumField

An Enum Field that also accepts boolean values.

Source code in comicbox/formats/base/fields/enum_fields.py
144
145
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
class EnumBooleanField(EnumField):
    """An Enum Field that also accepts boolean values."""

    YES = "Yes"
    NO = "No"
    TRUTHY = frozenset(
        {
            "1",
            "true",
            "yes",
        }
    )

    def _coerce_bool(self, value: Any) -> str:
        """
        Coerce a value the enum doesn't recognize into its yes or no value.

        The enum vocabulary wins first so multi valued enums keep their extra
        members. Only unrecognized values get read as a boolean, where anything
        that isn't truthy is no.
        """
        if self.get_enum(value):
            return value
        return self.YES if str(value).lower() in self.TRUTHY else self.NO

    @override
    def _deserialize(
        self, value: Enum | str | bool, attr, data, *args, **kwargs
    ) -> Any:
        if not isinstance(value, self.ENUM):
            value = self._coerce_bool(value)
        return super()._deserialize(value, attr, data, *args, **kwargs)

    @override
    def _serialize(self, value, *args, **kwargs) -> str | None:
        if value is not None and not isinstance(value, self.ENUM):
            value = self._coerce_bool(value)
        return super()._serialize(value, *args, **kwargs)

EnumField

Bases: FuzzyEnumMixin, Enum

Fuzzy lookup Enum field that allows caseless enum lookups with variations.

Source code in comicbox/formats/base/fields/enum_fields.py
 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
class EnumField(FuzzyEnumMixin, fields.Enum):
    """Fuzzy lookup Enum field that allows caseless enum lookups with variations."""

    ENUM = Enum

    def get_enum_map(self) -> dict:
        """Transform the ENUM_ALIAS_MAP into the enum lookup map and add the field enum to it as well."""
        enum_map = self.get_enum_alias_map()
        for enum in self.ENUM:
            self.add_enum_map_item(enum, enum, enum_map)
        return enum_map

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Use the enum."""
        super().__init__(self.ENUM, *args, by_value=StringField, **kwargs)
        enum_map = self.get_enum_map()
        self._enum_map = MappingProxyType(enum_map)

    @override
    def _deserialize(
        self,
        value: Enum | str,
        attr: str | None,
        data: Mapping[str, Any] | None,
        *args: Any,
        **kwargs: Any,
    ) -> Enum:
        enum = self.get_enum(value)
        enum = enum or value
        return super()._deserialize(enum, attr, data, *args, **kwargs)

    @override
    def _serialize(
        self, value: Enum | Any | None, *args: Any, **kwargs: Any
    ) -> str | None:
        if value is None:
            return None
        enum = self.get_enum(value)
        enum = enum or value
        return super()._serialize(enum, *args, **kwargs)

__init__(*args, **kwargs)

Use the enum.

Source code in comicbox/formats/base/fields/enum_fields.py
95
96
97
98
99
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Use the enum."""
    super().__init__(self.ENUM, *args, by_value=StringField, **kwargs)
    enum_map = self.get_enum_map()
    self._enum_map = MappingProxyType(enum_map)

get_enum_map()

Transform the ENUM_ALIAS_MAP into the enum lookup map and add the field enum to it as well.

Source code in comicbox/formats/base/fields/enum_fields.py
88
89
90
91
92
93
def get_enum_map(self) -> dict:
    """Transform the ENUM_ALIAS_MAP into the enum lookup map and add the field enum to it as well."""
    enum_map = self.get_enum_alias_map()
    for enum in self.ENUM:
        self.add_enum_map_item(enum, enum, enum_map)
    return enum_map

FuzzyEnumMixin

Fuzzy lookup get_enum() method that allows caseless enum lookups with variations.

Source code in comicbox/formats/base/fields/enum_fields.py
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
52
53
54
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
class FuzzyEnumMixin:
    """Fuzzy lookup get_enum() method that allows caseless enum lookups with variations."""

    ENUM_ALIAS_MAP = MappingProxyType({})

    @staticmethod
    def get_ordered_key_variations(key: str | Enum) -> tuple[str, ...]:
        """
        Get fuzzy lookup key variations, most literal first.

        Lookups try these in order, so the exact spelling always beats a
        variation that only matches after punctuation is collapsed.
        """
        new_key = key.value if isinstance(key, Enum) else key
        new_key = new_key.lower()
        variations = (
            new_key,
            new_key.replace(" ", ""),
            snakecase(new_key).replace("_", ""),
        )
        return tuple(dict.fromkeys(variations))

    @classmethod
    def get_key_variations(cls, key: str | Enum) -> set[str]:
        """Get enum caseless slightly fuzzy lookup key variations for a key."""
        return set(cls.get_ordered_key_variations(key))

    @classmethod
    def add_enum_map_item(cls, key: str | Enum, enum: Enum, enum_map: dict) -> None:
        """Add an enum or string to the lookup table with lowercase spaceless and spaced variations."""
        key_variations = cls.get_key_variations(key)
        for key_variation in key_variations:
            enum_map[key_variation] = enum

    def get_enum_alias_map(self) -> dict:
        """Transform the ENUM_ALIAS_MAP into the enum lookup map."""
        enum_map = {}
        for key, enum in self.ENUM_ALIAS_MAP.items():
            self.add_enum_map_item(key, enum, enum_map)
        return enum_map

    def get_enum(self, value: str | Enum) -> Enum | None:
        """
        Get an enum from the fuzzy lookup map.

        The map is keyed by every variation of every known spelling, so the
        lookup must generate the same variations of the value. Lowercasing
        alone matched "Cover Artist" and "CoverArtist" to different entries
        and missed snake_case input entirely.
        """
        key: str = value.value if isinstance(value, Enum) else str(value)
        enum_map = self._enum_map  # pyright: ignore[reportAttributeAccessIssue], # ty: ignore[missing-attribute]
        for key_variation in self.get_ordered_key_variations(key):
            if enum := enum_map.get(key_variation):
                return enum
        return None

add_enum_map_item(key, enum, enum_map) classmethod

Add an enum or string to the lookup table with lowercase spaceless and spaced variations.

Source code in comicbox/formats/base/fields/enum_fields.py
52
53
54
55
56
57
@classmethod
def add_enum_map_item(cls, key: str | Enum, enum: Enum, enum_map: dict) -> None:
    """Add an enum or string to the lookup table with lowercase spaceless and spaced variations."""
    key_variations = cls.get_key_variations(key)
    for key_variation in key_variations:
        enum_map[key_variation] = enum

get_enum(value)

Get an enum from the fuzzy lookup map.

The map is keyed by every variation of every known spelling, so the lookup must generate the same variations of the value. Lowercasing alone matched “Cover Artist” and “CoverArtist” to different entries and missed snake_case input entirely.

Source code in comicbox/formats/base/fields/enum_fields.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def get_enum(self, value: str | Enum) -> Enum | None:
    """
    Get an enum from the fuzzy lookup map.

    The map is keyed by every variation of every known spelling, so the
    lookup must generate the same variations of the value. Lowercasing
    alone matched "Cover Artist" and "CoverArtist" to different entries
    and missed snake_case input entirely.
    """
    key: str = value.value if isinstance(value, Enum) else str(value)
    enum_map = self._enum_map  # pyright: ignore[reportAttributeAccessIssue], # ty: ignore[missing-attribute]
    for key_variation in self.get_ordered_key_variations(key):
        if enum := enum_map.get(key_variation):
            return enum
    return None

get_enum_alias_map()

Transform the ENUM_ALIAS_MAP into the enum lookup map.

Source code in comicbox/formats/base/fields/enum_fields.py
59
60
61
62
63
64
def get_enum_alias_map(self) -> dict:
    """Transform the ENUM_ALIAS_MAP into the enum lookup map."""
    enum_map = {}
    for key, enum in self.ENUM_ALIAS_MAP.items():
        self.add_enum_map_item(key, enum, enum_map)
    return enum_map

get_key_variations(key) classmethod

Get enum caseless slightly fuzzy lookup key variations for a key.

Source code in comicbox/formats/base/fields/enum_fields.py
47
48
49
50
@classmethod
def get_key_variations(cls, key: str | Enum) -> set[str]:
    """Get enum caseless slightly fuzzy lookup key variations for a key."""
    return set(cls.get_ordered_key_variations(key))

get_ordered_key_variations(key) staticmethod

Get fuzzy lookup key variations, most literal first.

Lookups try these in order, so the exact spelling always beats a variation that only matches after punctuation is collapsed.

Source code in comicbox/formats/base/fields/enum_fields.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@staticmethod
def get_ordered_key_variations(key: str | Enum) -> tuple[str, ...]:
    """
    Get fuzzy lookup key variations, most literal first.

    Lookups try these in order, so the exact spelling always beats a
    variation that only matches after punctuation is collapsed.
    """
    new_key = key.value if isinstance(key, Enum) else key
    new_key = new_key.lower()
    variations = (
        new_key,
        new_key.replace(" ", ""),
        snakecase(new_key).replace("_", ""),
    )
    return tuple(dict.fromkeys(variations))

MangaField

Bases: EnumBooleanField

Comicbox manga field: says only whether the book is manga.

Source code in comicbox/formats/base/fields/enum_fields.py
205
206
207
208
class MangaField(EnumBooleanField):
    """Comicbox manga field: says only whether the book is manga."""

    ENUM = MangaEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]

OriginalFormatField

Bases: PrettifiedStringField

Prettify Original Format.

Source code in comicbox/formats/base/fields/enum_fields.py
265
266
267
268
class OriginalFormatField(PrettifiedStringField):
    """Prettify Original Format."""

    ENUM_ALIAS_MAP = GENERIC_FORMAT_MAP

PageTypeField

Bases: EnumField

ComicPageInfo Page Type Field.

Source code in comicbox/formats/base/fields/enum_fields.py
125
126
127
128
class PageTypeField(EnumField):
    """ComicPageInfo Page Type Field."""

    ENUM = ComicInfoPageTypeEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]

PrettifiedStringField

Bases: FuzzyEnumMixin, StringField

A string fields that tries to match to an enum and falls back to just titlecasing.

Source code in comicbox/formats/base/fields/enum_fields.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class PrettifiedStringField(FuzzyEnumMixin, StringField):
    """A string fields that tries to match to an enum and falls back to just titlecasing."""

    ENUM_ALIAS_MAP = MappingProxyType({})

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Use the enum."""
        super().__init__(*args, **kwargs)
        self._enum_map = MappingProxyType(self.get_enum_alias_map())

    def _prettify(self, value: str) -> str:
        """Conform a value to a known enum or titlecase."""
        enum = self.get_enum(value)
        if enum:
            value = enum.value
        else:
            value = titlecase(value)
            value = value.replace("  ", " ")
        return value

    @override
    def _deserialize(self, value: Any, *args: Any, **kwargs: Any) -> str:
        str_value: str = value.value if isinstance(value, Enum) else value
        str_value = super()._deserialize(str_value, *args, **kwargs)
        return self._prettify(str_value)

__init__(*args, **kwargs)

Use the enum.

Source code in comicbox/formats/base/fields/enum_fields.py
243
244
245
246
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Use the enum."""
    super().__init__(*args, **kwargs)
    self._enum_map = MappingProxyType(self.get_enum_alias_map())

ReadingDirectionField

Bases: EnumField

Reading direction enum.

Source code in comicbox/formats/base/fields/enum_fields.py
131
132
133
134
135
class ReadingDirectionField(EnumField):
    """Reading direction enum."""

    ENUM = ReadingDirectionEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]
    ENUM_ALIAS_MAP = READING_DIRECTION_ENUM_MAP

SeriesStatusField

Bases: EnumField

Series publication status enum.

Source code in comicbox/formats/base/fields/enum_fields.py
138
139
140
141
class SeriesStatusField(EnumField):
    """Series publication status enum."""

    ENUM = SeriesStatusEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]

YesNoEnum

Bases: Enum

Yes No Enum.

Source code in comicbox/formats/base/fields/enum_fields.py
211
212
213
214
215
216
class YesNoEnum(Enum):
    """Yes No Enum."""

    YES = "Yes"
    NO = "No"
    UNKNOWN = "Unknown"

YesNoField

Bases: EnumBooleanField

A yes no kind of boolean field.

Comicbox models these tags as plain booleans, so deserialize to bool. The schema’s Unknown means “not recorded”, which is no value at all.

Source code in comicbox/formats/base/fields/enum_fields.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class YesNoField(EnumBooleanField):
    """
    A yes no kind of boolean field.

    Comicbox models these tags as plain booleans, so deserialize to bool.
    The schema's Unknown means "not recorded", which is no value at all.
    """

    ENUM = YesNoEnum  # pyright: ignore[reportIncompatibleUnannotatedOverride]

    @override
    def _deserialize(self, value, attr, data, *args, **kwargs) -> Any:
        """Deserialize to a bool, or to None for the schema's Unknown."""
        enum = super()._deserialize(value, attr, data, *args, **kwargs)
        if enum == YesNoEnum.UNKNOWN:
            return None
        return enum == YesNoEnum.YES