Skip to content

comicbox.formats.base.fields.pycountry

Marshmallow pycountry fields.

CountryField

Bases: PyCountryField

PyCountry Country Field.

Source code in comicbox/formats/base/fields/pycountry.py
164
165
166
167
class CountryField(PyCountryField):
    """PyCountry Country Field."""

    DB: Database = pycountry.countries

LanguageField

Bases: PyCountryField

PyCountry Language Field.

Holds a BCP 47 tag. Only the primary language subtag is resolved with pycountry; script, region and variant subtags are kept as given, recased.

Source code in comicbox/formats/base/fields/pycountry.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class LanguageField(PyCountryField):
    """
    PyCountry Language Field.

    Holds a BCP 47 tag. Only the primary language subtag is resolved with
    pycountry; script, region and variant subtags are kept as given, recased.
    """

    DB: Database = pycountry.languages

    @override
    @classmethod
    def _split(cls, value: str) -> tuple[str, tuple[str, ...]]:
        """Split a BCP 47 tag into its primary language and recased subtags."""
        value = value.strip()
        if not _BCP47_RE.fullmatch(value):
            # Not a tag: a language name like "English", or garbage pycountry rejects.
            return value, ()
        primary, *subtags = value.split("-")
        suffix: list[str] = []
        singleton = False
        for subtag in subtags:
            # Extension and private use subtags follow a singleton, all lowercase.
            singleton = singleton or len(subtag) == 1
            suffix.append(subtag.lower() if singleton else _case_subtag(subtag))
        return primary, tuple(suffix)

PyCountryField

Bases: StringField, ABC

A pycountry value.

Source code in comicbox/formats/base/fields/pycountry.py
 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
 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
class PyCountryField(StringField, ABC):
    """A pycountry value."""

    DB: Database = pycountry.countries
    EMPTY_CODE = ""

    def __init__(
        self,
        *args: Any,
        serialize_name: bool = False,
        allow_empty: bool = False,
        **kwargs: Any,
    ) -> None:
        """Optionally serialize with full names."""
        self._serialize_name = serialize_name
        self._allow_empty = allow_empty
        super().__init__(*args, **kwargs)

    @staticmethod
    def _clean_name(name_obj: str) -> str | None:
        if not name_obj:
            return None
        name: str | None = StringField().deserialize(name_obj)
        if not name:
            return None
        return name.strip()

    @classmethod
    def _get_pycountry(cls, tag: str | None, name: str) -> Data | None:
        """Get pycountry object for a country or language tag."""
        try:
            cleaned = cls._clean_name(name)
            if not cleaned:
                return None

            name = cleaned
            # Language lookup fails for 'en' unless alpha_2 is specified.
            obj: Data | None = (
                cls.DB.get(alpha_2=name) if len(name) == 2 else cls.DB.lookup(name)  # noqa: PLR2004
            )
        except Exception as exc:
            logger.warning(exc)
            obj = None

        if obj is None:
            logger.warning(f"Couldn't find {tag} for {name}")

        return obj

    @classmethod
    def _to_alpha_code(cls, pc_obj: Any) -> str:
        code = cls.EMPTY_CODE
        for attr in _ALPHA_CODES:
            if code := getattr(pc_obj, attr, cls.EMPTY_CODE):
                break
        return code

    @classmethod
    def _split(cls, value: str) -> tuple[str, tuple[str, ...]]:
        """Split a value into the part pycountry resolves and a suffix to keep."""
        return value, ()

    @classmethod
    def _resolve(cls, attr: str | None, value: str, *, name: bool = False) -> str:
        """Resolve the pycountry part to a code or name and re-attach the suffix."""
        primary, suffix = cls._split(value)
        pc_obj = cls._get_pycountry(attr, primary)
        if not pc_obj:
            return cls.EMPTY_CODE
        if name:
            return pc_obj.name
        return "-".join((cls._to_alpha_code(pc_obj), *suffix))

    @override
    def _deserialize(
        self,
        value: Any,
        attr: str | None,
        *args: Any,
        **kwargs: Any,
    ) -> str:
        """Return the alpha 2 encoding."""
        value = super()._deserialize(value, attr, *args, **kwargs)
        return self._resolve(attr, value)

    @override
    def _serialize(
        self,
        value: str | None,
        attr: str | None,
        *args: Any,
        **kwargs: Any,
    ) -> str:
        """Return the long name."""
        serialized = super()._serialize(value, attr, *args, **kwargs)
        if not serialized:
            return self.EMPTY_CODE
        return self._resolve(attr, serialized, name=self._serialize_name)

__init__(*args, serialize_name=False, allow_empty=False, **kwargs)

Optionally serialize with full names.

Source code in comicbox/formats/base/fields/pycountry.py
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    *args: Any,
    serialize_name: bool = False,
    allow_empty: bool = False,
    **kwargs: Any,
) -> None:
    """Optionally serialize with full names."""
    self._serialize_name = serialize_name
    self._allow_empty = allow_empty
    super().__init__(*args, **kwargs)