Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_locale.py: 37%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""The Locale type: a named delta over (Lexicon, Policy), with a
2choice of languages.
4A Locale dissolves at parser construction (parser_for): the packs'
5languages are unioned with the base's recorded choice into one choice,
6recorded on the built Lexicon, which selects among the base's shipped
7readings by the file each sits in; the lexicon fragments join in pack
8order and the base's lexicon after them, their readings applying after
9the choice; and the PolicyPatch folds via apply_patch. Packs
10are pure data; they have no privileged capabilities
11(mechanisms.md#LOCALE-PACKS-PURE-DATA).
13Layering: imports _types, _lexicon and _policy only, and the compiled
14[rules] tables, nameparser/config/_rules.py, at call time (enforced by
15tests/v2/test_layering.py).
16"""
17from __future__ import annotations
19import dataclasses
20import re
21from collections.abc import Callable, Iterable, Mapping
22from dataclasses import dataclass, field
23from typing import Any
25from nameparser._lexicon import Lexicon, _canonical, _shown_choice
26from nameparser._policy import (
27 _ORDER_CONSTANT_NAMES, UNSET, PatronymicRule, PolicyPatch,
28 _classified_char, _reject_str_and_mapping,
29)
30from nameparser._types import ADDED_IN, _guarded_getstate, _guarded_setstate
32# a BCP 47 tag's shape: a language subtag and any number of subtags
33# after it; whether a vocabulary file holds it is parser_for's question,
34# asked of the reading index when the choice is applied
35_TAG = re.compile(r"[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*")
38@dataclass(frozen=True, slots=True)
39class Locale:
40 """A named, shareable bundle of vocabulary and behavior for a
41 naming tradition: a choice of languages, a lexicon fragment and a
42 policy patch, applied together by :func:`nameparser.parser_for`.
43 The packs shipped with
44 nameparser live in :mod:`nameparser.locales`; building your own
45 needs no registration -- construct one and pass it to
46 ``parser_for``. See the :doc:`locale packs guide </locales>` for
47 using and creating packs; to propose one for nameparser itself, see
48 ``CONTRIBUTING.md`` in the repository."""
50 #: Identifier, lowercase ``[a-z0-9_]+`` (e.g. "ru", "tr_az").
51 code: str
52 #: Vocabulary joined to the base parser's lexicon, before it, so the
53 #: base's own readings win where the two disagree, and applied after
54 #: the choice in ``languages``, which selects among the base's
55 #: shipped readings (decisions/vocabulary-model, 2026-11-02 #754,
56 #: item 3).
57 lexicon: Lexicon
58 #: Behavior changes folded onto the base policy (set-valued fields
59 #: union; script_orders merges by script; scalars override, later
60 #: pack wins).
61 policy: PolicyPatch = PolicyPatch()
62 #: The languages chosen, as BCP 47 tags (``{"pt"}``, ``{"pt-BR"}``):
63 #: ``parser_for`` unions the packs' languages, and the base's recorded
64 #: choice, into one choice, which
65 #: turns on the chosen languages' readings the default leaves off
66 #: and, on a word a chosen language holds a vocabulary reading of,
67 #: drops other languages' vocabulary readings. A tag selects its own
68 #: vocabulary file and its ancestors' (``pt-BR`` selects ``pt``
69 #: too), never its descendants'. Empty, the default, chooses
70 #: nothing, and the default vocabulary stands as it is. Added in
71 #: 3.0.
72 languages: frozenset[str] = field(
73 default=frozenset(), metadata={ADDED_IN: "3.0.0"})
75 # in the class body so @dataclass(slots=True) keeps them
76 __getstate__ = _guarded_getstate
77 __setstate__ = _guarded_setstate
79 def __post_init__(self) -> None:
80 if not isinstance(self.code, str):
81 raise TypeError(
82 f"Locale.code must be a str, got {self.code!r}"
83 )
84 if not self.code.strip():
85 raise ValueError(
86 f"Locale.code must be a non-empty string, got {self.code!r}"
87 )
88 if self.code != self.code.lower():
89 raise ValueError(
90 f"Locale.code must be lowercase, got {self.code!r}"
91 )
92 # Codes are registry keys (parser_for, third-party packs): every
93 # accepted character is supported forever, so pin the charset
94 # while relaxing later is still compatible. One separator only --
95 # allowing '-' too would make tr-az and tr_az distinct keys.
96 if not re.fullmatch(r"[a-z0-9_]+", self.code):
97 raise ValueError(
98 f"Locale.code must match [a-z0-9_]+, got {self.code!r}"
99 )
100 if not isinstance(self.lexicon, Lexicon):
101 raise TypeError(
102 f"Locale.lexicon must be a Lexicon, got {self.lexicon!r}"
103 )
104 if not isinstance(self.policy, PolicyPatch):
105 raise TypeError(
106 f"Locale.policy must be a PolicyPatch, got {self.policy!r}"
107 )
108 object.__setattr__(self, "languages", _tags(self.languages))
110 def __repr__(self) -> str:
111 # Bounded: shows the code and which Policy fields the patch sets,
112 # never the Lexicon contents or the patched values themselves
113 # (design rule, see nameparser._types module docstring).
114 patched = [f.name for f in dataclasses.fields(self.policy)
115 if getattr(self.policy, f.name) is not UNSET]
116 # a choice is shown by its tags while it is short, as one is
117 # (a pack chooses one or two), and by its size past that
118 if self.languages:
119 patched.insert(0, _shown_choice(self.languages))
120 suffix = f": {', '.join(patched)}" if patched else ""
121 return f"Locale({self.code!r}{suffix})"
124def _tags(value: object) -> frozenset[str]:
125 """`value` as Locale.languages stores it, each tag in canonical case,
126 or the TypeError or ValueError naming what is wrong with it."""
127 if isinstance(value, Mapping):
128 # not _reject_str_and_mapping's message: its {open: close} hint
129 # is about delimiter pairs, which a choice of languages never is
130 raise TypeError(
131 f"Locale.languages must be a set of BCP 47 tags, not a "
132 f"mapping: {value!r}. Write frozenset({{'pt'}}), or "
133 f"frozenset(mapping) to choose its keys")
134 _reject_str_and_mapping(value, "Locale.languages")
135 if not isinstance(value, Iterable):
136 raise TypeError(
137 f"Locale.languages must be an iterable of BCP 47 tags, e.g. "
138 f"frozenset({{'pt'}}), got {value!r}")
139 tags = frozenset(value)
140 for tag in sorted(tags, key=repr):
141 if not isinstance(tag, str):
142 raise TypeError(
143 f"Locale.languages entries must be str BCP 47 tags, got "
144 f"{tag!r}")
145 if not _TAG.fullmatch(tag):
146 raise ValueError(
147 f"Locale.languages entries must be BCP 47 tags such as 'pt' "
148 f"or 'pt-BR', got {tag!r}")
149 return frozenset(_canonical(tag) for tag in tags)
152#: How a compiled [rules] value becomes its PolicyPatch field's value,
153#: by key: an order by its constant's name written in the file's case
154#: ("family-first" is FAMILY_FIRST), a rule set by PatronymicRule's
155#: values. tools/vocab/build.py's RULE_KEYS checks the names at build
156#: time, and tests/v2/test_vocab.py holds the two tables to each other.
157_ORDERS = {name.lower().replace("_", "-"): order
158 for order, name in _ORDER_CONSTANT_NAMES.items()}
159_RULE_VALUES: dict[str, Callable[[Any], object]] = {
160 "name_order": lambda v: _ORDERS[v],
161 "patronymic_rules": lambda v: frozenset(PatronymicRule(r) for r in v),
162 "two_family_names": bool,
163 "two_given_names": bool,
164 "initials_as_family": bool,
165}
168def rules_patch(tag: str) -> PolicyPatch:
169 """The policy patch compiled from the [rules] table of the
170 vocabulary file `tag` (``"ru"`` for ru.toml), which a shipped pack
171 carries as its ``policy`` (#754, 4f): each key is the Policy field
172 of the same name, so a rule a pack turns on is a Policy field and a
173 Locale holds no rules of its own. Raises KeyError naming the files
174 that hold a table when `tag`'s holds none."""
175 from nameparser.config._rules import RULES
177 tables = dict(RULES)
178 if tag not in tables:
179 raise KeyError(
180 f"no vocabulary file {tag!r} holds a [rules] table; the files "
181 f"that do: {', '.join(sorted(tables))}")
182 values = {key: _RULE_VALUES[key](value) for key, value in tables[tag]}
183 # Known mypy limitation with **dict-unpacked construction; see the
184 # full explanation at Lexicon._edit in _lexicon.py.
185 return PolicyPatch(**values) # type: ignore[arg-type]
188def deviates_by_two_family_names(name: str) -> bool:
189 """The DEVIATES declaration of a pack whose patch turns on
190 ``Policy.two_family_names`` (rules/O6), the es, es_ar, cs, sk, hr,
191 sl, pt_br and pt_pt packs, and of the given-name list the es, es_ar,
192 pt_br and pt_pt packs carry beside it, which acts only where O6 does. O6 acts only on a name of three
193 or more name words, so a name declares that holds three or more
194 words, commas read as spaces,
195 or three or more units counting each run of letters and each word
196 holding no letter: the tokenizer may split one word into two runs
197 (a zero-width space, a Hangul name segmented), and a word of no
198 letter (``1``, ``-``) is a name word all the same. Titles, suffixes
199 and a family comma count here though O6 reads none of them, which
200 over-declares, the safe direction."""
201 pieces = name.replace(",", " ").split()
202 letterless = sum(1 for piece in pieces if not any(ch.isalpha() for ch in piece))
203 return len(pieces) >= 3 or _letter_runs(name) + letterless >= 3
206def _letter_runs(text: str) -> int:
207 """The runs of letters in `text`, whatever separates one from the
208 next: a hyphen, a zero-width space or an interpunct, which the
209 tokenizer may read as separators (rules/T1, T2, T3). A run opening
210 with a character of a script the script table classifies counts
211 twice, since segmentation may divide it into a family and a given
212 name (rules/W1): the table every script-conditional rule reads, so
213 a character W1 can divide is one this counts twice, and one outside
214 it (a compatibility jamo, an archaic kana) is a word W1 never divides
215 (#1087). A letter written with a combining mark splits a run, which
216 over-declares."""
217 runs, inside = 0, False
218 for ch in text:
219 letter = ch.isalpha()
220 if letter and not inside:
221 runs += 2 if _classified_char(ch) else 1
222 inside = letter
223 return runs