Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_parser.py: 22%
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"""Parser and the module-level parse() for the 2.0 API.
3Layering: sits on _types/_lexicon/_policy/_locale/_pipeline, and imports
4_match, _suggest and _reading_index at call time only; never imports
5_render (enforced by tests/v2/test_layering.py).
7_default_parser is THE one sanctioned module-level global: a
8functools.cache'd frozen Parser over default config.
9"""
10from __future__ import annotations
12import dataclasses
13import functools
14import warnings
15from collections.abc import Iterable
16from dataclasses import dataclass, field
17from typing import TYPE_CHECKING
19from nameparser._lexicon import _rechosen_masks
20from nameparser._lexicon import Lexicon
21from nameparser._locale import Locale
22from nameparser._pipeline import run
23from nameparser._pipeline._assemble import assemble
24from nameparser._pipeline._post_rules import suffix_entries
25from nameparser._pipeline._state import ParseState
26from nameparser._pipeline._vocab import _SCRIPT_MATCHERS
27from nameparser._policy import (
28 _EAST_ASIAN_SCRIPTS, _JA_SCRIPTS, UNSET, Policy, PolicyPatch, _Unset,
29 apply_patch,
30)
31from nameparser._types import (
32 FOLDED_TAG, ParsedName, Role, Segmenter, Token, _guarded_getstate,
33 _guarded_setstate, _validated_field_strings,
34)
36if TYPE_CHECKING:
37 from nameparser._match import Matching, Outcome
38 from nameparser._suggest import Suggestion
41@dataclass(frozen=True, slots=True)
42class Parser:
43 """A configured name parser: a :class:`Lexicon` (vocabulary) plus
44 a :class:`Policy` (behavior), both defaulted when omitted. Build
45 one when you need non-default configuration, build it once, and
46 call :meth:`parse` many times -- it is immutable and thread-safe.
48 An optional keyword-only ``segmenter`` (a :data:`~nameparser.Segmenter`)
49 plugs in outside knowledge of where an unspaced CJK token divides --
50 Japanese kanji names, which no bundled list can settle. It is
51 consulted only for a token the segmentation stage gates in and the
52 vocabulary DECLINES, so a locale pack's surnames always win where
53 they match; returning None declines in turn and the token stays
54 whole. Two promises narrow when one is supplied (the first is
55 rules/A1's Accepted bullet "The one exception to totality"):
56 parse-totality gains its one exception -- an exception raised by
57 the segmenter propagates, because a user-supplied callable's own
58 error is a user-code error, not a content error -- and this Parser
59 pickles only if its segmenter does (a module-level function
60 pickles; a lambda or closure does not). With no segmenter, both
61 promises hold unconditionally: all validity checking happens at
62 construction, so a Parser that constructs successfully cannot fail
63 at parse time on any str content.
65 (The None field defaults resolve in __post_init__; after
66 construction lexicon and policy are always non-None -- the
67 annotations state the steady-state truth, hence the assignment
68 ignores on the defaults.)"""
70 lexicon: Lexicon = None # type: ignore[assignment] # None -> default()
71 policy: Policy = None # type: ignore[assignment] # None -> Policy()
72 #: An optional hook supplying outside knowledge of where an unspaced
73 #: token divides -- see the class docstring; None leaves such tokens
74 #: whole. Keyword-only, so the reserved growth stays additive:
75 #: positional construction keeps its two-argument shape.
76 segmenter: Segmenter | None = field(default=None, kw_only=True)
78 # in the class body so @dataclass(slots=True) keeps them
79 __getstate__ = _guarded_getstate
80 __setstate__ = _guarded_setstate
82 def __post_init__(self) -> None:
83 if self.lexicon is None:
84 object.__setattr__(self, "lexicon", Lexicon.default())
85 elif not isinstance(self.lexicon, Lexicon):
86 raise TypeError(
87 f"lexicon must be a Lexicon or None, got {self.lexicon!r}")
88 if self.policy is None:
89 object.__setattr__(self, "policy", Policy())
90 elif not isinstance(self.policy, Policy):
91 raise TypeError(
92 f"policy must be a Policy or None, got {self.policy!r}")
93 if self.segmenter is not None and not callable(self.segmenter):
94 raise TypeError(
95 f"segmenter must be callable or None, got {self.segmenter!r}")
96 # A configuration gap that used to be silent (#272's API, made
97 # loud before 2.1.0): segment_scripts can activate a script
98 # that neither the vocabulary nor a segmenter can ever divide
99 # -- the JA pack's whole shape, when its segmenter is
100 # forgotten. The parser then behaves identically to a working
101 # one minus the feature, which reads as "not working" with no
102 # signal why. Statically decidable here, so say it here; a
103 # warning rather than an error because the segmentation-inert pack is a
104 # pinned, deliberate property (a JA registration must be safe
105 # without the extra), and warnings are filterable by the rare
106 # caller who wants exactly that.
107 if self.segmenter is None:
108 uncovered = sorted(
109 script.value
110 for script in self.policy.segment_scripts
111 # only the East Asian scripts divide (#1237)
112 if script in _EAST_ASIAN_SCRIPTS
113 and not any(_SCRIPT_MATCHERS[script](entry)
114 for entry in self.lexicon._sets.surnames))
115 if uncovered:
116 names = ", ".join(uncovered)
117 one = len(uncovered) == 1
118 # the ja hint only where a Japanese script is among the
119 # dead ones -- a hangul-only gap (a from-scratch
120 # lexicon under the default policy) has different
121 # remedies, and pointing it at ja_segmenter would be a
122 # non sequitur
123 ja_hint = (
124 " For Japanese, pass "
125 "segmenter=locales.ja_segmenter() (install with: "
126 "pip install 'nameparser[ja]')."
127 if {s.value for s in _JA_SCRIPTS} & set(uncovered)
128 else "")
129 warnings.warn(
130 f"Policy.segment_scripts activates {names} but the "
131 f"vocabulary has no surnames in "
132 f"{'that script' if one else 'those scripts'} "
133 f"and no segmenter is configured: unspaced names "
134 f"written in {'it' if one else 'them'} will never "
135 f"divide. Supply covering surnames, pass a "
136 f"segmenter, or deactivate with "
137 f"Policy(segment_scripts=frozenset()).{ja_hint}",
138 UserWarning, stacklevel=3)
140 def __repr__(self) -> str:
141 # composes the two bounded component reprs; the
142 # segmenter shows by name, and only when one is set, so the
143 # default Parser's repr is unchanged
144 seg = ""
145 if self.segmenter is not None:
146 # never repr() the callable itself: a partial reprs its
147 # bound arguments and a callable instance its address, both
148 # unbounded -- the class name is the bounded fallback
149 name = (getattr(self.segmenter, "__qualname__", None)
150 or type(self.segmenter).__name__)
151 seg = f", segmenter={name}"
152 return f"Parser({self.lexicon!r}, {self.policy!r}{seg})"
154 # -- properties ------------------------------------------------------
156 @property
157 def languages(self) -> frozenset[str]:
158 """The languages this parser's vocabulary is chosen under,
159 :attr:`Lexicon.languages` read through: set by
160 :func:`parser_for`, empty where none was chosen. Added in
161 3.0."""
162 return self.lexicon.languages
164 @property
165 def strict(self) -> bool:
166 """Whether the choice is strict, :attr:`Lexicon.strict` read
167 through. Added in 3.0."""
168 return self.lexicon.strict
170 def parse(self, text: str) -> ParsedName:
171 """Parse one name string into a :class:`ParsedName`. Never
172 raises on string content (unparseable input yields empty
173 fields plus ambiguities); non-str raises TypeError eagerly,
174 with a decode hint for bytes (bytes support ended with 1.x).
175 The one exception to that totality is a configured
176 ``segmenter``, whose own exceptions propagate (see the class
177 docstring)."""
178 if isinstance(text, bytes):
179 raise TypeError(
180 "parse() takes str, not bytes -- decode first, e.g. "
181 "raw.decode('utf-8')")
182 if not isinstance(text, str):
183 raise TypeError(f"parse() takes str, got {text!r}")
184 state = ParseState(original=text, lexicon=self.lexicon,
185 policy=self.policy, segmenter=self.segmenter)
186 return assemble(run(state))
188 # -- editing ----------------------------------------------------------
190 def revise(self, name: ParsedName, **fields: str) -> ParsedName:
191 """:meth:`ParsedName.replace` with this parser's vocabulary:
192 each value is tokenized and classified by a full sub-parse, so
193 the stable tags survive and the tag-driven views
194 (family_particles, initials(), the suffix join, and since #407
195 capitalized()) behave as if the text had been parsed. The
196 value is classified ON ITS OWN, though -- a word whose reading
197 depends on surrounding context may classify differently than
198 it would in place, and a glued CJK honorific the whole name
199 kept on an initial may peel in the value. The sub-parse's role
200 choices and ambiguities are discarded -- every harvested token
201 takes the named field's role -- and its structural behavior
202 applies: delimiter characters do not become tokens, and a
203 maiden marker is consumed as in parsing -- mid-value always,
204 and leading a DELIMITED value under a policy routing that pair
205 to maiden, where "(née Jones)" revises to "Jones" while the
206 bare "née Jones" keeps its marker, a leading marker in an
207 undelimited value being no marker at all (#329).
208 A suffix value's ENTRY structure is derived from the value's
209 own commas after the role is forced, by the rule a whole name
210 uses: a comma parts two credentials and a space joins them, so
211 ``revise(n, suffix="MD PhD")`` is one entry and a name's
212 rendered suffix revises back to itself wherever the value's
213 words read as the whole name read them -- the honorific peel
214 above was the one corpus exception of 368 suffix-bearing names,
215 2026-09-06 (#511). A second came with #601/#602: a suffix
216 holding a maiden marker the whole name left a word, whose
217 value read on its own takes the clause and drops the marker
218 ('Jane Doe PhD nee Smith' renders 'PhD nee Smith', which
219 revises to 'PhD Smith'), three corpus names on 2026-10-04. A delimiter the policy names through
220 ``extra_suffix_delimiters`` parts a value only where the
221 value's own words, read as a name, give it a tail segment for
222 the core to be dropped on; a run of post-nominals has none,
223 with or without a comma of its own (``"MD PhD - FACS"`` and
224 ``"MD, PhD - FACS"`` both keep the dash as a word), so write a
225 comma at the boundary you want rather than the delimiter.
226 Tokens are synthetic (span=None); original is unchanged; a
227 value with no name content (empty, whitespace, or punctuation
228 only) clears the field; ambiguities referencing replaced
229 tokens are dropped."""
230 if not isinstance(name, ParsedName):
231 raise TypeError(f"revise() takes a ParsedName, got {name!r}")
232 replaced = _validated_field_strings(fields)
233 harvested: dict[Role, tuple[Token, ...]] = {}
234 for role, value in replaced.items():
235 # the same construction parse() makes, spelled twice
236 # rather than through a helper: routing parse() through
237 # one cost a frame per parse on the hot path (py3.11,
238 # 2026-09-06: 415 calls/name against 414 without it, in a
239 # 402-418 band), the same trade _mark_suffix_entries
240 # refused, one row over
241 state = run(ParseState(original=value, lexicon=self.lexicon,
242 policy=self.policy,
243 segmenter=self.segmenter))
244 dropped = set(state.dropped)
245 # Force the role BEFORE the entry pass: it keys on
246 # Role.SUFFIX, and a bare value's sub-parse reads its words
247 # as a name ('VC PhD' is a title and a family there), so
248 # inside the sub-parse it joined nothing. The sub-parse's
249 # tags are KEPT, "joined" included: a within-piece mark
250 # (the Ph. D. merge) is role-blind and right for every
251 # role, and a clear was measured and backed out --
252 # decisions/R1 (2026-09-06 #511) carries the rest: the
253 # between-piece mark that rides onto a non-suffix role, and
254 # which views read it. Dropped tokens keep their role: the
255 # pass filters them by index and assemble omits them.
256 forced = tuple(
257 tok if i in dropped
258 else dataclasses.replace(tok, role=role)
259 for i, tok in enumerate(state.tokens))
260 # rules/R1: "a run of post-nominals written with spaces
261 # renders with spaces, and one written with commas keeps
262 # them" -- the same pass post_rules runs last, over the
263 # value's own comma offsets, so the harvest carries exactly
264 # the entry structure the value's commas describe. Run for
265 # every role: for a non-suffix role it is a no-op, kept
266 # unconditional as the simpler contract, revise() being off
267 # the call-count band.
268 entried = suffix_entries(
269 dataclasses.replace(state, tokens=forced))
270 harvested[role] = tuple(
271 Token(t.text, None, role, t.tags - {FOLDED_TAG})
272 for t in assemble(entried).tokens)
273 return name._with_field_tokens(harvested)
275 # -- comparison -------------------------------------------------------
277 def matches(self, a: str | ParsedName, b: str | ParsedName) -> bool:
278 """Component-wise case-insensitive comparison of two names,
279 parsing str arguments with THIS parser.
280 :meth:`ParsedName.matches` parses its str argument with the
281 DEFAULT parser instead -- for names parsed with a custom
282 Parser, use this method."""
283 if isinstance(a, str):
284 a = self.parse(a)
285 elif not isinstance(a, ParsedName):
286 raise TypeError(f"matches() takes str or ParsedName, got {a!r}")
287 if isinstance(b, str):
288 b = self.parse(b)
289 elif not isinstance(b, ParsedName):
290 raise TypeError(f"matches() takes str or ParsedName, got {b!r}")
291 return a.comparison_key() == b.comparison_key()
293 def matching(
294 self, accept: Iterable[Outcome | str] | None = None, *,
295 other_readings: bool = False,
296 ) -> Matching:
297 """A :class:`~nameparser.Matching` bound to THIS parser,
298 so its ``check`` and ``keys`` parse str arguments with this
299 parser's lexicon and policy. A ParsedName argument is compared
300 as given, whatever parser produced it. ``accept`` is the
301 iterable of outcomes counted as consistent; None takes the
302 default set, and any other value replaces it, so extend the
303 default with ``parser.matching(accept=parser.matching().accept
304 | {"family-initial"})``. ``other_readings=True`` also searches
305 each side's other readings (``Matching.other_readings``). A
306 value is validated by ``Matching``, which raises for a bad one."""
307 from nameparser._match import DEFAULT_ACCEPT, Matching
308 return Matching(
309 self, DEFAULT_ACCEPT if accept is None else accept, # type: ignore[arg-type]
310 other_readings)
312 def suggest(self, names: Iterable[str]) -> Suggestion:
313 """The settings a group of names suggests, with THIS parser as
314 the base: a :class:`~nameparser.Suggestion` whose ``parser``
315 reads the group. ``names`` is any iterable of str the caller
316 declares to be one group (one source, one convention), read
317 once. Each name casts votes on its name order, its patronymic
318 shape and, where the switch is weighed (below),
319 ``two_family_names``, read with this parser's lexicon past the
320 titles it lists at the head and the post-nominals at the end; a
321 name of fewer than two words once those are read past casts
322 none, and so does a name with a comma, unless only
323 post-nominals follow the comma. A patronymic votes only where
324 the patronymic rule reads one, and an East Slavic one votes on
325 the order too, by where it stands: last for family-first
326 (``Sidorov Ivan Petrovich``), in the middle for given-first
327 (``Ivan Petrovich Sidorov``). A trailing initial
328 (``Smith J.``) votes only where at least three names, and 60% of the
329 group's names holding a name word, end in initials no other
330 signal in the same name contradicts. A capitals word of two
331 or three letters ending a name in mixed case (``Armitage JO``),
332 or opening it with no capitals word after it (``AM Hoy``, ``NG
333 Emily``), casts no capitals vote, being joined initials as
334 often as a short surname. The ending one casts no surname
335 vote of its own, and where it is itself a listed surname
336 (``Zhou NG``) the name casts none: its first word is usually
337 the given name there, and the table cannot tell the two
338 readings apart. A name opening in one casts no surname vote.
339 ``name_order`` is
340 decided in either direction, keeping this parser's family-first
341 spelling where it has one, where at least two names vote for
342 one end, they are more than two thirds of the names casting
343 an order vote, and they are at least 1% of the group's names a
344 comma does not leave out: in a long list where few names vote, a
345 few stray votes decide nothing, and the order evidence's note
346 says so. A patronymic rule is decided where more than four
347 in five of the names that cast a vote carry its patronymic (and
348 at least five do), for the East Slavic and the Turkic rule alike;
349 a name whose only vote was a set-aside trailing initial counts
350 among the names that cast one, and the patronymic evidence's
351 note says how many.
352 A group decided East Slavic gets the rule and reads
353 given-first, the order the rule reorders each name under,
354 unless its names' own votes decide family-first, as a list of
355 patronymics written last does, which the rule never overrides: there a
356 ``FAMILY_FIRST_GIVEN_LAST`` parser gets ``FAMILY_FIRST``, under
357 which the patronymic is not read as the given name (``Popov Ivan
358 Ivanovich``). One case keeps a declared order instead: under a
359 ``FAMILY_FIRST`` parser whose names' votes do not decide
360 given-first, where more of the names carrying the patronymic
361 write it last (``Sidorov Ivan Petrovich``) than in the middle
362 (``Ivan Petrovich Sidorov``), the group keeps that order and
363 gets the rule alone, which reorders no name there and fills the
364 ``patronymic`` view; the names written the other way get no
365 given-first order, and the patronymic evidence's note counts
366 them. A tie, and a ``FAMILY_FIRST_GIVEN_LAST`` parser whose
367 names' votes do not decide family-first, get the given-first
368 order with the rule. A Turkic group
369 gets the rule alone, its order decided by its names' own votes.
370 ``initials_as_family`` (rules/O8) is turned on where one run of
371 letters ends at least two names and at least half of the names
372 ending in letters (Nepal's ``B K``), and a group decided so
373 casts no trailing-initial vote on its order; a group never turns
374 it off, nor turns it on under a base reading names family first,
375 where letters ending a name are never read as its family.
376 ``capitals_as_family`` (rules/O9) is turned on where
377 at least two names, and more than two thirds of the names with
378 evidence either way, write the family in capitals: the rule,
379 asked of the name parsed with the switch on, reads as its family
380 a word in capitals of four letters or more that is no listed
381 credential or numeral and that this parser, reading the name,
382 does not take for a title (``Jean DUPONT``, ``Mary BISHOP``),
383 against a name whose family the switch would move onto a word
384 this parser reads as a title (``MISS Ann Berg``, ``DR DUPONT
385 Jean``) and a name of two
386 words or more in mixed case with none in capitals, read past its
387 titles and post-nominals (``DR Ann Berg``, ``John Smith FRCS``);
388 a name against a decided switch is among ``disagreeing()``. Two or three
389 capitals are no evidence (``Zhi LI``, or initials, ``AM Hoy``),
390 and only a name holding a word in capitals is parsed. A group
391 never turns it off, nor turns it on under a base with
392 ``unlisted_caps_suffixes=CapsSuffixes.EVERYWHERE``, beside which
393 it cannot be set; it is decided apart from the order, which the
394 capitals in a name vote on as before. ``two_family_names``
395 (rules/O6) is weighed last, and only where the rest of the
396 suggestion reads given-first with the East Slavic rule off: each
397 name is parsed with the switch off and on, and where the switch
398 takes a word into the family, a common surname there votes for
399 it (``García`` in ``Gabriel García Márquez``), a common given
400 name casts no vote (``María`` in ``Ana María López``), and a
401 father's name votes against it. It is turned on where at least
402 three names vote for it, more than 30% of every name the switch
403 would change and more than those against; a group never turns
404 it off; a father's name the switch would take disagrees with it.
405 A caller who knows a list is Spanish or Portuguese does better
406 with the language's pack (``locales.ES``, ``locales.PT_BR``,
407 ``locales.PT_PT``), whose given names the switch leaves out of
408 the family. A setting the votes do not
409 decide keeps this parser's value, so
410 an empty group, or one with no votes, suggests no change. A
411 bare str, bytes, a mapping or a non-str item raises TypeError.
413 Measured on groups drawn from real names written in a known
414 order (:ref:`suggest-limits`; the dated tables are in the
415 source repository's docs/design/decisions/group-suggestion.md),
416 these figures give a general idea and will differ for every
417 dataset. A group written in this parser's own order kept it in
418 at least 95% of groups from 2 to 2,000 names, and in 97% for
419 nearly every kind, save three kinds of list: given names in
420 capitals (``ANNA Smith``), whose capitals read as a family name;
421 nothing but two or three joined initials (``AM Hoy``), which
422 kept it in just under 95% of groups of 50 and 93% of 100; and
423 nothing but given names that are common surnames elsewhere
424 (``Cooper``, ``Burke``), read the wrong way round. A group
425 written the other way round takes more names to move the base:
426 from 5 for Chinese, Taiwanese, Korean, Czech, Polish, Italian
427 and Russian names to 50 for Indian ones and 200 for Bangladeshi
428 ones. A group whose votes fall short of the thresholds keeps the
429 base rather than guess. ``capitals_as_family`` was suggested in
430 at least 95% of groups from 4 names for holders who typed their
431 family name in capitals, and from 10 where many of the surnames
432 are two or three letters (China, Korea, Vietnam and Taiwan); of
433 the lists that do not write their family names so, only the one
434 writing its given names in capitals was suggested it. A name
435 wholly in one case carries no evidence.
436 """
437 from nameparser._suggest import suggest
438 return suggest(self, names)
440 # -- rendering delegates ----------------------------------------------
442 def capitalized(self, name: ParsedName, *,
443 force: bool = False) -> ParsedName:
444 """:meth:`ParsedName.capitalized` under THIS parser's lexicon.
445 The no-argument form of that method uses the DEFAULT lexicon --
446 for names parsed with a custom Parser, use this method."""
447 if not isinstance(name, ParsedName):
448 raise TypeError(f"capitalized() takes a ParsedName, got {name!r}")
449 return name.capitalized(self.lexicon, force=force)
452@functools.cache
453def _default_parser() -> Parser:
454 return Parser()
457def parse(text: str) -> ParsedName:
458 """Parse a name with the default configuration and return a
459 :class:`ParsedName`. Equivalent to ``Parser().parse(text)``; build
460 your own :class:`Parser` (or use :func:`parser_for`) for custom
461 vocabulary or behavior. Never raises on string content."""
462 return _default_parser().parse(text)
465def _reading_index_selected(languages: frozenset[str],
466 strict: bool = False) -> frozenset[str]:
467 # the reading index loads on first lookup, so a caller who chooses
468 # no language never imports it (decisions/vocabulary-model, 3a)
469 from nameparser._reading_index import selected
470 return selected(languages, strict=strict)
473def _rewrapped(exc: Exception, message: str) -> Exception:
474 """`exc`'s message with `message` before it, as a plain TypeError or
475 ValueError: a subclass may take other constructor arguments
476 (_lexicon._MaskValueError takes three)."""
477 return (TypeError if isinstance(exc, TypeError) else ValueError)(
478 f"{message}: {exc}")
481def _with_packs(lexicon: Lexicon, locales: tuple[Locale, ...],
482 languages: frozenset[str], strict: bool) -> Lexicon:
483 """`lexicon` with the packs' fragments joined before it, in pack
484 order, so its own readings outrank every pack's and a later pack's
485 an earlier one's, and the choice of `languages` recorded, where the
486 compile and its refusals happen (decisions/vocabulary-model,
487 2026-11-02 #754, items 3 and 4). The case masks follow the same
488 order: the choice moves `lexicon`'s, the packs' are laid over them,
489 and a mask `lexicon` holds as the choice leaves the shipped one is
490 no statement of the caller's, so a pack's mask of the word wins it,
491 as a pack's readings win over the shipped ones."""
492 fragments = Lexicon.empty()
493 for loc in locales:
494 fragments = fragments | loc.lexicon
495 joined = fragments | lexicon
496 if languages:
497 chosen = _reading_index_selected(languages, strict)
498 mine = dict(_rechosen_masks(lexicon, chosen, strict))
499 shipped = dict(_rechosen_masks(Lexicon.default(), chosen, strict))
500 else:
501 mine = dict(lexicon.capitalization_exceptions)
502 shipped = dict(Lexicon.default().capitalization_exceptions)
503 masks = dict(mine)
504 for k, v in fragments.capitalization_exceptions:
505 if k not in mine or mine[k] == shipped.get(k):
506 masks[k] = v
507 cap = tuple(sorted(masks.items()))
508 if not languages and cap == joined.capitalization_exceptions:
509 return joined
510 return dataclasses.replace(
511 joined, capitalization_exceptions=cap, _languages=languages,
512 _strict=strict)
515def _failed_layer(lexicon: Lexicon, locales: tuple[Locale, ...],
516 languages: frozenset[str], strict: bool) -> str:
517 """The layer a failed `_with_packs` names (rules/D2): the first pack
518 whose fragment fails the join, or, where base's lexicon fails under
519 the choice alone, the languages and the packs that chose them.
520 Taken on the error path only, by building again pack by pack."""
521 def fails(packs: tuple[Locale, ...]) -> bool:
522 try:
523 _with_packs(lexicon, packs, languages, strict)
524 except (TypeError, ValueError):
525 return True
526 return False
528 if not fails(()):
529 for n, loc in enumerate(locales, 1):
530 if fails(locales[:n]):
531 return f"while applying locale {loc.code!r}"
532 # base's lexicon fails alone only under the choice: with no
533 # languages a join fails only on a pack, found above
534 choosers = [repr(loc.code) for loc in locales if loc.languages]
535 if lexicon.languages:
536 choosers.append("base")
537 return (f"while applying the languages chosen, "
538 f"{', '.join(sorted(languages))} (by {', '.join(choosers)})")
541def parser_for(*locales: Locale, base: Parser | None = None,
542 segmenter: Segmenter | None | _Unset = UNSET,
543 strict: bool | _Unset = UNSET) -> Parser:
544 """The packs' ``languages`` and base's recorded choice unioned into
545 one choice, recorded on the built parser's lexicon
546 (:attr:`Parser.languages`), so the order of the packs, and whether
547 they were chained through ``base``, does not change it:
548 ``parser_for(EN, base=parser_for(PT))`` reads as ``parser_for(PT,
549 EN)``. The packs' lexicon fragments are joined left-to-right and
550 base's lexicon after them, so a caller's own readings outrank every
551 pack's and a later pack's an earlier one's; the choice filters the
552 shipped readings and every lexicon's ``add`` and ``remove`` apply
553 after it, so a choice never drops a caller's word. A caller's
554 reading that cannot stand beside one the choice turns on raises
555 ValueError here, naming the call (decisions/vocabulary-model,
556 2026-11-02 #754, items 3 and 4). Policy patches apply left-to-right
557 (later wins; set-valued fields union and script_orders merges by
558 script, per the patch metadata). A
559 pack that chooses no language leaves the base vocabulary exactly
560 as it is.
562 ``strict=True`` makes the choice strict: only the chosen languages'
563 vocabulary files are compiled, each tag selecting its own and its
564 ancestors' as a plain choice does, plus mul.toml, the words every
565 language writes alike (``Dr``, ``Prof``, ``PhD``, ``MSc``, the
566 numerals), and a native-script word's readings (one with a letter
567 and no Latin letter), name readings included, as a plain choice of
568 the same languages keeps them; every other file's readings leave,
569 und.toml's among them, and with them the markers they derive. It is
570 for single-origin data (``parser_for(Locale(code="ko",
571 lexicon=Lexicon.empty(), languages=frozenset({"ko"})),
572 strict=True)`` reads ``Kim Do Hyun``
573 with no Portuguese particle ``do``). A caller's own readings and the
574 packs' fragments apply after it, as after a plain choice, and the
575 policy patches unchanged. ``strict`` has three states, as
576 ``segmenter`` does: omitted (:data:`~nameparser.UNSET`) keeps base's
577 recorded strictness, ``False`` on a strict base raises ValueError, a
578 strict choice not being undone by a later call, and ``True`` on a
579 plain one makes the whole choice strict. A strict choice accepts a
580 language whose file holds no reading a parse reads yet (``hu``,
581 whose familiar forms only name matching reads), which a plain
582 one refuses as changing nothing, and raises ValueError when the
583 packs choose no language, since it would then keep no language's
584 own words, only mul.toml's and native-script words' readings
585 (decisions/vocabulary-model, 2026-10-30 #753, file-strict, and
586 2026-10-31 #753, phase 3j).
588 Validation errors raised while applying a
589 pack are wrapped with that pack's identity (rule D2) --
590 PolicyPatch validates lazily, so with stacked packs the raw error
591 would otherwise point at nothing. Two packs setting the same SCALAR
592 field to different values is a declared conflict: UserWarning, later
593 wins; two setting it to the same value agree, and nothing is warned.
595 A ``segmenter`` is passed straight through to the built Parser --
596 ``parser_for(locales.JA, segmenter=locales.ja_segmenter())`` is how
597 a pack and a segmenter combine, since packs are pure data and
598 cannot supply one. The argument has THREE states, the same
599 :data:`~nameparser.UNSET` spelling a PolicyPatch field uses, because
600 None is a meaningful value here and not an absence: omitted (UNSET)
601 carries base's segmenter through unchanged; a callable OVERRIDES
602 base's (later wins, the rule scalar policy fields follow); and an
603 explicit ``None`` CLEARS base's, which is how you derive an
604 unsegmented parser from a segmented one without rebuilding its
605 lexicon and policy by hand."""
606 if base is not None and not isinstance(base, Parser):
607 raise TypeError(f"base must be a Parser or None, got {base!r}")
608 if strict is not UNSET and not isinstance(strict, bool):
609 raise TypeError(f"strict must be True or False, got {strict!r}")
610 for loc in locales:
611 if not isinstance(loc, Locale):
612 raise TypeError(f"parser_for() takes Locale packs, got {loc!r}")
613 lexicon = base.lexicon if base is not None else Lexicon.default()
614 policy = base.policy if base is not None else Policy()
615 # Resolved here rather than at the return because the return builds
616 # a FRESH Parser: any field not listed there silently takes its
617 # default, and a dropped segmenter would be invisible. UNSET, not
618 # None, is what "not given" means -- None is the CLEAR request, and
619 # collapsing the two would make an explicit
620 # parser_for(..., segmenter=None) silently inherit the very
621 # segmenter it was asked to drop.
622 if segmenter is UNSET:
623 segmenter = base.segmenter if base is not None else None
624 # strict's three states, as segmenter's: omitted keeps base's
625 # strictness; an explicit False on a strict base is refused, a
626 # strict choice not being undone by a later call, and an explicit
627 # True makes a plain base's choice strict (decisions/vocabulary-model,
628 # 2026-11-02 #754, sub-phase 4i-c)
629 if isinstance(strict, _Unset):
630 strict = lexicon.strict
631 elif lexicon.strict and not strict:
632 raise ValueError(
633 "base's lexicon was chosen with strict=True, and a chained "
634 "choice keeps it: leave strict out or pass strict=True, or "
635 "choose every language in one call from the default lexicon, "
636 "base's packs included, parser_for(*packs, strict=False)")
637 # one choice for all the packs and the base's, so applying them is
638 # order-free; each pack's tags are checked on their own first, so a
639 # tag no file holds is reported with the pack that named it
640 # (rules/D2)
641 languages = lexicon.languages
642 for loc in locales:
643 if loc.languages:
644 try:
645 _reading_index_selected(loc.languages, strict)
646 except ValueError as exc:
647 raise _rewrapped(
648 exc, f"while applying locale {loc.code!r}") from exc
649 languages |= loc.languages
650 if strict and not languages:
651 raise ValueError(_no_strict_language(locales))
652 try:
653 lexicon = _with_packs(lexicon, locales, languages, strict)
654 except (TypeError, ValueError) as exc:
655 # rules/D2: "applying a locale pack wraps any such error with
656 # the locale's code, so a stacked configuration names which
657 # layer broke" -- the pack whose fragment broke the join, or,
658 # where base's own lexicon clashes with the choice, the
659 # languages and the packs that chose them (history:
660 # decisions/vocabulary-model, 2026-10-29 3b and 2026-11-02 #754,
661 # sub-phase 4i-c)
662 raise _rewrapped(exc, _failed_layer(
663 lexicon, locales, languages, strict)) from exc
664 # each scalar field's setter so far and the value it left in the
665 # policy: a later pack leaving another value overrides it, which is
666 # warned; one leaving the same value (cs and sk's two_family_names)
667 # agrees. Compared as the applied Policy holds it, canonical.
668 scalar_setters: dict[str, tuple[str, object]] = {}
669 scalars = [f.name for f in dataclasses.fields(PolicyPatch)
670 if f.metadata.get("compose") not in ("union", "by-script")]
671 # script_orders composes by script: a later pack setting one script
672 # to another order overrides that entry, which is warned the same way
673 script_setters: dict[object, tuple[str, object]] = {}
674 for loc in locales:
675 # rules/D2: "applying a locale pack wraps any such error with
676 # the locale's code, so a stacked configuration names which layer
677 # broke" (history: decisions/D2)
678 try:
679 policy = apply_patch(policy, loc.policy)
680 except (TypeError, ValueError) as exc:
681 raise _rewrapped(exc, f"while applying locale {loc.code!r}") from exc
682 for name in scalars:
683 if getattr(loc.policy, name) is UNSET:
684 continue
685 value = getattr(policy, name)
686 if name in scalar_setters:
687 code, held = scalar_setters[name]
688 if code != loc.code and held != value:
689 warnings.warn(
690 f"locale {loc.code!r} overrides scalar policy field "
691 f"{name!r} already set by locale {code!r}; later wins",
692 UserWarning, stacklevel=2)
693 scalar_setters[name] = (loc.code, value)
694 if loc.policy.script_orders is not UNSET:
695 patched = {s for s, _ in loc.policy.script_orders}
696 for script, order in policy.script_orders:
697 if script not in patched:
698 continue
699 if script in script_setters:
700 code, held = script_setters[script]
701 if code != loc.code and held != order:
702 warnings.warn(
703 f"locale {loc.code!r} overrides the script_orders "
704 f"entry for {script.value!r} already set by "
705 f"locale {code!r}; later wins",
706 UserWarning, stacklevel=2)
707 script_setters[script] = (loc.code, order)
708 # rules/D1: "constructing a parser that activates division for
709 # scripts with no covering surnames and no segmenter warns at
710 # construction, naming the dead scripts and each way out"
711 # (history: decisions/D1)
712 # Construction warnings (the segmenterless-activation check in
713 # Parser.__post_init__) re-emit from THIS frame: its stacklevel is
714 # sized for direct Parser(...) construction, and through this
715 # function's extra frame the default single-line rendering would
716 # point into the library instead of at the caller -- the exact
717 # call the message tells them to change.
718 with warnings.catch_warnings(record=True) as caught:
719 warnings.simplefilter("always")
720 built = Parser(lexicon=lexicon, policy=policy, segmenter=segmenter)
721 for w in caught:
722 warnings.warn(w.message, stacklevel=2)
723 return built
726def _no_strict_language(locales: tuple[Locale, ...]) -> str:
727 """The refusal of a strict call that chooses no language, which
728 would keep only mul.toml's and native-script words' readings, dropping
729 every language's own words in silence. The fix it offers is a pack
730 choosing the first pack's code where that is a language a strict
731 choice accepts, else ``en``."""
732 tag = "en"
733 if locales:
734 try:
735 _reading_index_selected(frozenset({locales[0].code}), True)
736 except ValueError:
737 pass
738 else:
739 tag = locales[0].code
740 codes = ", ".join(repr(loc.code) for loc in locales)
741 named = ("no pack was given" if not locales
742 else f"the pack {codes} chooses none" if len(locales) == 1
743 else f"the packs {codes} choose none")
744 return (f"strict=True keeps only the chosen languages' vocabulary, "
745 f"the shared words (mul.toml) and other scripts' words, and "
746 f"{named}, so it would keep the shared and other scripts' "
747 f"words alone; add "
748 f"a pack that chooses a language, e.g. "
749 f"Locale(code={tag!r}, lexicon=Lexicon.empty(), "
750 f"languages=frozenset({{{tag!r}}})), or drop strict=True")