Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_policy.py: 48%
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"""Immutable behavior configuration for the 2.0 API.
3Layering: imports nameparser._types only (enforced by
4tests/v2/test_layering.py).
5"""
6from __future__ import annotations
8import dataclasses
9import re
10import unicodedata
11from collections.abc import Callable, Iterable, Mapping
12from dataclasses import dataclass, field
13from enum import Enum, StrEnum, auto
14from types import MappingProxyType
15from typing import Any, Literal
17from nameparser._types import (
18 ADDED_IN, FAMILY_FIRST, FAMILY_FIRST_GIVEN_LAST, GIVEN_FIRST, Role,
19 _coerce_enum,
20 _guarded_getstate, _guarded_setstate, _reject_bare_string_order,
21 _require_iterable, _validated_order,
22)
25class PatronymicRule(StrEnum):
26 """Stable rule names (API); implementations live in the pipeline.
27 Enable via ``Policy(patronymic_rules={...})`` or, more commonly, a
28 locale pack (:mod:`nameparser.locales`)."""
30 #: East Slavic formal order: "Sidorov Ivan Petrovich"
31 #: (family, given, patronymic) is detected by the patronymic
32 #: ending and reordered, and a middle word with the ending fills
33 #: ParsedName.patronymic. Enabled by locales.RU.
34 EAST_SLAVIC = "east-slavic"
35 #: Turkic patronymic markers: a standalone "oglu"/"qizi"/"kyzy"
36 #: (etc.) binds to the preceding name as a patronymic, the two
37 #: filling ParsedName.patronymic. Enabled by locales.TR_AZ.
38 TURKIC = "turkic"
41class CapsSuffixes(StrEnum):
42 """Where ``Policy.unlisted_caps_suffixes`` reads an unlisted
43 all-caps word as a credential (#516, #564)."""
45 #: Nowhere: such a word is name material in every position, as
46 #: 2.3 read it.
47 OFF = "off"
48 #: Only after a comma, behind two or more name words ("John Smith,
49 #: XYZ" gives suffix ``XYZ``), where a word in mixed case that opens
50 #: with two capitals or ends in one reads so too ("Jane Smith, MRes").
51 #: The default: the all-caps SURNAME convention ("Jean DUPONT",
52 #: "DUPONT, Jean") never writes the capitals there.
53 AFTER_COMMA = "after-comma"
54 #: After a comma and ending a name with no comma ("John Smith XYZ"
55 #: gives suffix ``XYZ``), where the all-caps surname convention
56 #: does write them -- "Jean Pierre DUPONT" then gives family
57 #: ``Pierre``, suffix ``DUPONT``. Cannot be set with
58 #: ``Policy.capitals_as_family``, which reads that word as the
59 #: family. Its other positions read a word wholly in capitals only:
60 #: a surname typed without its apostrophe ("Alex Lee ONeill") ends
61 #: a name there.
62 EVERYWHERE = "everywhere"
65class Script(StrEnum):
66 """Writing systems the parser can key SCRIPT-CONDITIONAL behavior
67 on: per-script name order (``Policy.script_orders``) and
68 unspaced-name segmentation (``Policy.segment_scripts``). The rule
69 that admits these (amendment 2026-07-27): script-conditional
70 DEFAULT behavior only where the script itself determines the
71 convention -- Latin-script input is never affected. A member no
72 default keys on (KATAKANA, CYRILLIC) is there for a caller's or a
73 pack's own entry, licensed by that choice (rules/W4). The codepoint
74 table backing these members is internal."""
76 #: Chinese Hanzi -- and Japanese Kanji: a pure-Han string cannot
77 #: say which language it is, which is fine for ORDER (both write
78 #: family-first natively) and exactly why Han SEGMENTATION is
79 #: opt-in, per language: locales.ZH brings the Chinese surname
80 #: list, locales.JA activates the same stage for a pluggable
81 #: segmenter to divide kanji names with.
82 HAN = "han"
83 #: Korean Hangul (precomposed syllables and the conjoining jamo).
84 #: Unambiguously Korean.
85 HANGUL = "hangul"
86 #: Japanese hiragana. Never transcribes foreign names, so a mixed
87 #: kanji+kana token (高橋みなみ) is Japanese and resolves HERE --
88 #: this member is the carrier key in script_orders/segment_scripts.
89 HIRAGANA = "hiragana"
90 #: Japanese katakana, full-width and halfwidth (タロウ) alike. A
91 #: PURE-katakana token may be a transcribed foreign name in its
92 #: original order (マイケル) or a Japanese name's reading written
93 #: family-first (ヤマダ タロウ, and legacy halfwidth data), and the
94 #: script cannot say which, so no default behavior keys on this
95 #: member; it exists so the classifier can name what it
96 #: deliberately declines. A caller who knows their katakana is
97 #: Japanese maps it to FAMILY_FIRST in script_orders.
98 KATAKANA = "katakana"
99 #: Cyrillic. Written for many languages in both orders (Russian
100 #: given-first, Mongolian father's name first), so the script
101 #: settles no order and no default keys on it: it exists so a
102 #: caller's or a pack's script_orders entry can, as locales.MN's
103 #: does, licensed by the caller's choice of that pack (#1237). Not
104 #: among the scripts the interpunct and the two-family-names count
105 #: read (_EAST_ASIAN_SCRIPTS), and, having no row in
106 #: _SCRIPT_PROPERTIES, writes initials: Cyrillic names abbreviate.
107 CYRILLIC = "cyrillic"
110# Codepoint ranges per Script (#271). This integer table is the single
111# source of truth for what a script covers; every matcher DERIVES from
112# it -- _pipeline/_vocab.py compiles its per-script patterns from it,
113# and it is importable from the pipeline and the locale packs alike,
114# so the packs' predicates build on it too, through _script_matcher
115# below (the table lives here rather than in the pipeline because
116# packs must not import the pipeline).
117# HAN: the ideographic iteration mark U+3005 and the shime mark
118# U+3006, the URO plus Extension A, the compatibility block, and the
119# supplementary-plane block
120# (Ext B-I + CJK Compat Ideographs Supplement, 0x20000-0x323AF) --
121# rare surnames are the biggest real source of supplementary-plane
122# hanzi in personal names (e.g. 𠮷田's 𠮷, U+20BB7), so leaving them
123# out silently mis-orders those names; unassigned gaps inside the span
124# are harmless, since no real name contains an unassigned codepoint.
125# U+3005 々 is the block-vs-Script case, running the OPPOSITE way to
126# U+30FB below: 々 already IS Script=Han under UAX #24 (Scripts.txt
127# reads `3005 ; Han`), but it sits in CJK Symbols and Punctuation,
128# outside every CJK ideograph block this table spans -- so a
129# singleton entry was what a BLOCK table needed to reach a character
130# the Script property would have classified correctly for free. It
131# earns the reach: 々 repeats the preceding kanji and appears only
132# inside Han-written names -- 佐々木 (Sasaki, a top-20 Japanese
133# surname), 野々村, 奈々. Omitting it made 佐々木 a mixed-script token:
134# the name reversed and never gated into segmentation.
135# U+3006 〆 (the shime mark) extends that singleton to a two-codepoint
136# span on a DIFFERENT justification: unlike 々, 〆 is Script=Common
137# under UAX #24, so this is the table deliberately reaching PAST the
138# Script property, not around a block boundary -- justified because
139# within personal names 〆 appears solely in Japanese surnames (〆木
140# Shimeki, 〆谷 Shimetani, 〆野) -- its other uses (the envelope
141# closing mark, 〆切) never reach a name parser -- and it appears in
142# no other script's names.
143# HANGUL: the precomposed syllables and the three conjoining jamo
144# blocks (U+1100-U+11FF, Extended-A U+A960-U+A97F, Extended-B
145# U+D7B0-U+D7FF), the letters Unicode composes a syllable from (#1087).
146# A syllable typed decomposed is jamo, and a reader of raw characters
147# (tokenize's interpunct flank, rules/T3) must see it as hangul
148# (decisions/nfd-shapes, #1087). All three blocks, though the extended
149# ones hold only archaic jamo no modern name uses, the ground the kana
150# entry below leaves out the supplementary kana on: the U+1100 block
151# carries archaic jamo too, so no modern-only line can be drawn at
152# block granularity. The compatibility jamo U+3131-U+318E are not
153# conjoining and compose nothing; they stay out (rules/R7 initials
154# 'ㄱㄴ 김' as 'ㄱ.').
155# HIRAGANA/KATAKANA (#272): the two kana blocks, each in full. There
156# IS a supplementary-plane kana repertoire (Kana Supplement, Kana
157# Extended-A/B, Small Kana Extension, U+1AFF0-U+1B16F, a few hundred
158# assigned codepoints -- no exact count here, it moves with the
159# Unicode version) but none of it is WORTH chasing the way Han's astral
160# block is: those codepoints are hentaigana and other archaic/
161# phonetic-extension forms no modern Japanese name uses, unlike
162# supplementary Han, which real surnames genuinely need. The Katakana
163# Phonetic Extensions block (U+31F0-U+31FF, 16 small katakana for Ainu
164# transcription) is excluded for the same reason -- no modern Japanese
165# personal name uses them. Halfwidth kana (U+FF65-U+FF9F, #594) IS
166# katakana here: legacy bank, payroll and CSV data written for JIS X
167# 0201 systems spells names in it, and 山田 タロウ must read as 山田 タロウ
168# does. Classifying it is a range, not a fold. rules/T's Background
169# says "nothing rewrites the text before parsing", which rules out a
170# fold at tokenize, and an NFKC fold at classification would reach far
171# past the kana (fullwidth Latin, ㈱), and when #594 decided it a
172# voicing mark with no precomposed form to join (ア゙) folded to the
173# combining U+3099, which is in the HIRAGANA block -- so the folded
174# token took the kana license and a wholly-katakana name turned
175# family-first (decisions/W4; #596 has since given every voicing
176# mark after a kana its base's script, see below). The span takes
177# in the halfwidth nakaguro U+FF65, which tokenize turns into a separator,
178# on the same direct-call grounds as U+30FB below, and the voicing
179# marks U+FF9E/U+FF9F: they are spacing characters (category Lm) that
180# NFC never composes into their base, there being no precomposed
181# halfwidth voiced kana, so a span ending at U+FF9D would leave ダ
182# unclassified. It stops short
183# of U+FF61-U+FF64, the halfwidth CJK punctuation, whose U+FF61 is a
184# full stop (_lexicon.FULL_STOPS).
185# This table classifies by Unicode BLOCK, not the UAX #24 Script
186# property: U+30A0, U+30FB (the middle dot), and U+30FC (the
187# prolonged sound mark) all carry Script=Common under UAX #24, and the
188# four kana voicing marks U+3099-U+309C split two and two -- U+3099
189# and U+309A are the COMBINING forms (Script=Inherited), U+309B and
190# U+309C the spacing ones (Script=Common) -- yet every one of them is
191# needed here, and block membership, not the Script property, is what
192# puts them in range. Those four are in range only for a mark that
193# follows no kana: a mark voices the kana it follows, in either
194# syllabary, so classification deletes every mark that follows a
195# kana and the token takes its base's script (#596,
196# _vocab._normalized_for_script) -- ア゙イ is katakana, not katakana
197# plus hiragana. The katakana block's upper end (U+30FF) takes in
198# the middle dot U+30FB, kept rather than carved out for a smaller
199# reason than it looks: tokenize (#272 Task 2b) turns U+30FB into a
200# token separator, so no real parse shows the classifier a string
201# containing one. It is kept so that a DIRECT whole-string call --
202# effective_script (_pipeline/_vocab.py) on "マイケル・ジャクソン", which
203# the unit tests (tests/v2/pipeline/test_vocab.py) make -- still
204# classifies instead of returning None. The ranges below must
205# stay mutually disjoint: single_script (_pipeline/_vocab.py) returns
206# the FIRST covering entry (dict iteration order), so an overlapping
207# future script would make the result order-dependent instead of
208# well-defined.
209#: The precomposed hangul syllables, and the three conjoining jamo
210#: blocks HANGUL holds beside them (#1087), named so a test can state
211#: the table before #1087 by subtracting them rather than copying spans.
212_HANGUL_SYLLABLES = (0xAC00, 0xD7A3)
213_CONJOINING_JAMO = ((0x1100, 0x11FF), (0xA960, 0xA97F), (0xD7B0, 0xD7FF))
215_SCRIPT_RANGES: dict[Script, tuple[tuple[int, int], ...]] = {
216 Script.HAN: ((0x3005, 0x3006), (0x3400, 0x4DBF), (0x4E00, 0x9FFF),
217 (0xF900, 0xFAFF), (0x20000, 0x323AF)),
218 Script.HANGUL: tuple(sorted((_HANGUL_SYLLABLES, *_CONJOINING_JAMO))),
219 Script.HIRAGANA: ((0x3040, 0x309F),),
220 Script.KATAKANA: ((0x30A0, 0x30FF), (0xFF65, 0xFF9F)),
221 # The Cyrillic block and Cyrillic Supplement, Extended-A, -B and -C
222 # (#1237); a decomposed letter is composed before classification
223 # (_vocab._normalized_for_script) where a precomposed form exists,
224 # so a stress mark with none (е́) leaves its word unclassified
225 Script.CYRILLIC: ((0x0400, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF),
226 (0xA640, 0xA69F)),
227}
229#: The scripts whose characters rules/T3's interpunct flank and the
230#: two-family-names declaration's run count read as classified: the
231#: East Asian ones, every _SCRIPT_RANGES entry but CYRILLIC, which
232#: keys only a declared script order (#1237).
233_EAST_ASIAN_SCRIPTS = (Script.HAN, Script.HANGUL, Script.HIRAGANA,
234 Script.KATAKANA)
236#: The Japanese repertoire: the three scripts Japanese names draw on.
237#: The kana license (_pipeline/_vocab.py's effective_script), the ja
238#: pack's DEVIATES, and the segmenter adapter's repertoire guard all
239#: quantify over this one union (HANGUL simply omitted).
240_JA_SCRIPTS = (Script.HAN, Script.HIRAGANA, Script.KATAKANA)
244def _letter_units(text: str) -> list[int]:
245 """How many letters each run of letters in `text` holds, a combining
246 mark kept in the run of the letter it marks and every other
247 character dividing two runs."""
248 units, letters, in_run = [], 0, False
249 for ch in text:
250 if ch.isalpha():
251 letters += 1
252 in_run = True
253 elif in_run and unicodedata.category(ch) in ("Mn", "Mc", "Me"):
254 continue
255 elif in_run:
256 units.append(letters)
257 letters, in_run = 0, False
258 if in_run:
259 units.append(letters)
260 return units
263def initials_as_family_may_move(text: str) -> bool:
264 """Whether Policy.initials_as_family may move `text`: rules/O8 moves
265 only letters standing two or more in a row, so a name it moves holds
266 two runs in a row of one letter each, wherever they stand and
267 whatever divides them. Every character but a letter and a combining
268 mark divides a run here, wider than any separator the parse reads
269 (a zero-width character, `・`, a glued comma or bracket), so the
270 test over-declares, the safe direction, and never misses a name the
271 rule moves. locales.NE's DEVIATES and Parser.suggest's letter runs
272 both ask it."""
273 units = _letter_units(text)
274 return any(a == 1 == b for a, b in zip(units, units[1:]))
277def _script_matcher(*scripts: Script,
278 whole: bool = False) -> Callable[[str], bool]:
279 """A predicate over strings, compiled once from the union of the
280 named scripts' spans in _SCRIPT_RANGES. whole=False: True when the
281 string CONTAINS any such character -- DEVIATES' contract, where
282 over-declaring is the gate's safe direction. whole=True: True when
283 the string is non-empty and consists WHOLLY of such characters,
284 as the ja adapter's repertoire guard and _vocab's script
285 classifiers ask. Meant to be called at MODULE
286 scope: "compiled once" is per matcher, and each call compiles a
287 fresh pattern. The compiled pattern lives in the closure ON
288 PURPOSE, and the compilation lives HERE rather than in a pack-
289 local closure: tests/v2/test_locales.py classifies any pack module
290 holding a module-level re.Pattern as a marker pack needing rotator
291 branch coverage, and its registry gate goes further -- a pack that
292 so much as IMPORTS re without exposing such a pattern fails
293 "imports re but exposes no module-level pattern" -- so a
294 range-declaring pack must not import re at all; predicates built
295 here keep the packs invisible to that sweep by construction (and
296 spare _vocab's derived matchers a declaration row in
297 tests/v2/test_regex_sync.py's completeness sweep, which scans the
298 pipeline modules (plus _render) for private module-level
299 patterns)."""
300 if not scripts:
301 raise ValueError("_script_matcher needs at least one Script")
302 return _ranges_matcher(tuple(span for script in scripts
303 for span in _SCRIPT_RANGES[script]),
304 whole=whole)
307def _ranges_pattern(ranges: Iterable[tuple[int, int]]) -> re.Pattern[str]:
308 """One or more characters of the union of `ranges`, compiled: the
309 pattern _ranges_matcher wraps, and the one a caller searches at C
310 level where a frame per call matters (_vocab's spelled-initial
311 veto)."""
312 cls = "".join(f"\\U{lo:08x}-\\U{hi:08x}" for lo, hi in ranges)
313 if not cls:
314 raise ValueError("_ranges_pattern needs at least one range")
315 return re.compile(f"[{cls}]+")
318def _ranges_matcher(ranges: Iterable[tuple[int, int]],
319 whole: bool = False) -> Callable[[str], bool]:
320 """_script_matcher over codepoint spans rather than Script members:
321 the form the script-property table (_SCRIPT_PROPERTIES) is read
322 in, its rows not being keyed by Script."""
323 # one pattern serves both modes: fullmatch of [cls]+ is wholly-of,
324 # and search over [cls]+ is exactly contains-any
325 pattern = _ranges_pattern(ranges)
326 match = pattern.fullmatch if whole else pattern.search
328 def matcher(text: str) -> bool:
329 return match(text) is not None
330 return matcher
333#: One character, or a string wholly, of an East Asian script
334#: (_EAST_ASIAN_SCRIPTS):
335#: the question the interpunct's flank guard (rules/T3) and the
336#: two-family-names declaration's run count (_locale) both ask, defined
337#: once here because _locale may not import the pipeline (#1087).
338_classified_char = _script_matcher(*_EAST_ASIAN_SCRIPTS, whole=True)
341# ---------------------------------------------------------------------
342# The script-property table (#1256). Every rule that asks one of four
343# questions about a script's writing -- whether it has case for the
344# name-case contrast, whether it writes initials, whether it writes
345# period abbreviations, whether a bare run of its letters with a period
346# is a Latin initial spelled out -- reads its answer here, and nowhere
347# else (other script facts, the order a script settles or the marks a
348# Thai name writes, live with their rules), so that adding a script is one
349# row and a misjudged answer sits in one place. Private, and keyed by
350# a private name rather than by Script: that enum holds what a caller
351# can key a setting on, and membership there settles nothing about
352# case or initials. mechanisms.md#SCRIPT-PROPERTY-TABLE ("a reader selects the spans of the column that is ITS question")
353# names the pattern. Each answer is a writing CONVENTION, never the
354# script's typology: Devanagari is an abugida and abbreviates a name
355# to a letter and a period ("म. गांधी"), as Cyrillic does ("А. С.
356# Пушкин"), while Arabic, an abjad, writes a letter and a period for a
357# title (د.) and, in the name lists measured, almost none for a name. decisions/script-properties holds each row's
358# history and the recompute recipes, the CLDR count that decides
359# "writes initials" where a locale states it among them.
361@dataclass(frozen=True, slots=True)
362class _ScriptRow:
363 """One script's answers. `has_case` False: the name-case contrast
364 reads no case in it, though Unicode gives it one; None: Unicode's
365 case properties answer (a letter whose upper and lower case differ
366 has case). `writes_initials`: a letter of it with a period can
367 stand in for a name (rules/T5, R7). `period_abbreviations`: a run
368 of its letters with a period may be an abbreviation, and so a title
369 by shape (rules/H2). `spells_initials`: a bare run of its letters
370 with a period is a Latin initial spelled out (एम. for M.), never a
371 title by shape (rules/H2's Brahmic Except). `reason` and `source`
372 say why, in one line each."""
374 ranges: tuple[tuple[int, int], ...]
375 has_case: Literal[False] | None
376 writes_initials: bool
377 period_abbreviations: bool
378 spells_initials: bool
379 reason: str
380 source: str
382 __getstate__ = _guarded_getstate
383 __setstate__ = _guarded_setstate
386_SCRIPT_PROPERTIES: Mapping[str, _ScriptRow] = MappingProxyType({
387 "han": _ScriptRow(
388 _SCRIPT_RANGES[Script.HAN], None, False, False, False,
389 "no Chinese or Japanese writer shortens a name to one character "
390 "and a period, nor any word to a run of characters with one",
391 "CLDR zh's initialPattern is {0}, no period, and ja uses an "
392 "initial in 0 of 29 patterns (2026-08-02 and 2026-11-12; #320, "
393 "#323)"),
394 "hangul": _ScriptRow(
395 _SCRIPT_RANGES[Script.HANGUL], None, False, False, False,
396 "no Korean writer shortens a name or a word to a letter and a "
397 "period; the conjoining jamo a decomposed syllable is written in "
398 "are Hangul too",
399 "CLDR ko uses an initial in 0 of 32 patterns (2026-08-02 and "
400 "2026-11-12; #320, #1087)"),
401 "hiragana": _ScriptRow(
402 _SCRIPT_RANGES[Script.HIRAGANA], None, False, False, False,
403 "no Japanese writer shortens a name or a word to a kana and a "
404 "period",
405 "CLDR ja uses an initial in 0 of 29 patterns (2026-08-02 and "
406 "2026-11-12; #320)"),
407 "katakana": _ScriptRow(
408 _SCRIPT_RANGES[Script.KATAKANA], None, False, False, False,
409 "no Japanese writer shortens a name or a word to a kana and a "
410 "period",
411 "CLDR ja uses an initial in 0 of 29 patterns (2026-08-02 and "
412 "2026-11-12; #320)"),
413 "brahmic": _ScriptRow(
414 ((0x0900, 0x0DFF),), None, True, True, True,
415 "the ten Brahmic scripts from Devanagari to Sinhala write "
416 "initials, and spell a Latin one out by its sound with no vowel "
417 "sign (एम. for M.), a run of letters the title shape misreads",
418 "rules/H2's Brahmic Except, decisions/H2 (#1191)"),
419 "georgian": _ScriptRow(
420 ((0x10D0, 0x10FF), (0x1C90, 0x1CBF)), False, True, True, False,
421 "Mkhedruli has no capitals in use; Mtavruli, its upper case since "
422 "Unicode 11, is written only for a whole word in capitals, so no "
423 "letter's case is a choice made against the rest of the name, and "
424 "a name in Mtavruli repairs to Mkhedruli (rules/R4). The "
425 "ecclesiastical Asomtavruli and Nuskhuri, a pair that does write "
426 "initial capitals, are not in the row",
427 "#1222 (the contrast), #1223 (case repair); CLDR ka uses an "
428 "initial in 1 of 15 authored patterns (2026-11-12)"),
429 "myanmar": _ScriptRow(
430 ((0x1000, 0x109F), (0xA9E0, 0xA9FF), (0xAA60, 0xAA7F),
431 (0x116D0, 0x116FF)), None, False, True, False,
432 "no Burmese writer shortens a name to a letter and a period in "
433 "Burmese script (none in 2,604 Wikidata labels, #1234); whether "
434 "it writes period abbreviations is not decided, and reads as before",
435 "decided 2026-11-12 on #1256, by amendment, from the convention; "
436 "CLDR my's patterns are en's, equal in 42 of 42 by the copy test "
437 "(cldr main c0b65ae3, 2026-11-12), so the recipe does not answer"),
438 "thai": _ScriptRow(
439 ((0x0E00, 0x0E7F),), None, False, True, False,
440 "no Thai name is abbreviated to a letter and a period, but a title "
441 "is written short with periods between its consonants (ดร., "
442 "ร.ต.อ.), so it writes period abbreviations",
443 "CLDR th uses an initial in 0 of 20 authored patterns, a block of "
444 "its own (12 of 20 equal to en's by the copy test; 2026-08-02 "
445 "#320, re-run 2026-11-12, #1256)"),
446 "lao": _ScriptRow(
447 ((0x0E80, 0x0EFF),), None, False, True, False,
448 "no Lao name is abbreviated to a letter and a period, but a title "
449 "is written short with a period (ດຣ.), so it writes period "
450 "abbreviations, as Thai does",
451 "CLDR lo uses an initial in 0 of 37 authored patterns, writing the "
452 "name in full in each of the 6 where en's has an initial (cldr "
453 "main c0b65ae3, 2026-11-20; #1380)"),
454 "arabic": _ScriptRow(
455 ((0x0600, 0x06FF), (0x0750, 0x077F), (0x0870, 0x089F),
456 (0x08A0, 0x08FF), (0xFB50, 0xFDFF), (0xFE70, 0xFEFC),
457 (0x10EC0, 0x10EFF)), None, False, True, False,
458 "the Arabic-script name lists measured write a letter and a period "
459 "for a title (د., أ.د., م.م.) and almost never for a name, so it "
460 "writes period abbreviations and no initials; Persian and Urdu "
461 "are covered on thin evidence (decisions/script-properties' Open)",
462 "decided 2026-11-19 on #1149 from usage, against CLDR ar's 8 of 42 "
463 "authored patterns with an initial: ORCID's 6,291 Arabic-script "
464 "names write every opening letter with a period as a title, "
465 "Wikidata's 212 none (decisions/script-properties)"),
466})
469def _ranges_where(column: str, value: object) -> tuple[tuple[int, int], ...]:
470 """Every span of the rows whose `column` holds `value`, in table
471 order: the one way a reader selects rows."""
472 return tuple(span for row in _SCRIPT_PROPERTIES.values()
473 if getattr(row, column) == value for span in row.ranges)
476def _read_spans(column: str, value: object) -> tuple[tuple[int, int], ...]:
477 """`_ranges_where`, for a column a reader is built from at import:
478 no row selected would build a reader that matches nothing, so the
479 import fails naming the column and the fix."""
480 spans = _ranges_where(column, value)
481 if not spans:
482 raise ValueError(
483 f"no row of _policy._SCRIPT_PROPERTIES has {column}={value!r}, "
484 f"so the readers of that column would match nothing: add the "
485 f"row that answers it, or drop the readers")
486 return spans
489#: The scripts that write no initials (rules/T5, R7), as spans: read
490#: by _vocab's initial veto, _render's initials() and the name match.
491_NO_INITIAL_RANGES = _read_spans("writes_initials", False)
492#: The scripts that write no period abbreviation, so a word of theirs
493#: wearing a period is never a title by shape (rules/H2, #323).
494_NO_ABBREVIATION_RANGES = _read_spans("period_abbreviations", False)
495#: The scripts in which a bare run of letters with a period is a
496#: spelled Latin initial (rules/H2's Brahmic Except, #1191).
497_SPELLED_INITIAL_RANGES = _read_spans("spells_initials", True)
498#: The letters the name-case contrast reads no case in (rules/S6's "a
499#: script with no case to write in"), mapped to None so that
500#: `str.translate` drops them at C level before a contrast is read:
501#: _vocab.is_one_case, _vocab.ambiguous_lean, _render's R5 gate and
502#: S8's name word behind a credential (two predicates in _pieces); and
503#: _render._capitalize writes a first letter in it in its lower case (R4).
504#: Only the letters Unicode gives a case are listed, the others being
505#: caseless to the comparison already. Read-only, as the table is: the
506#: one sanctioned mutable global is the default parser (AGENTS.md).
507_CASELESS_LETTERS: Mapping[int, None] = MappingProxyType({
508 cp: None
509 for lo, hi in _read_spans("has_case", False)
510 for cp in range(lo, hi + 1)
511 if chr(cp).upper() != chr(cp).lower()})
514# Order-spec constants (#270), defined in _types beside Role since
515# ParsedName.order holds one (3.0, #754) and _types imports nothing
516# internal; re-exported here, where Policy validates name_order.
518_ORDER_CONSTANT_NAMES: dict[tuple[Role, ...], str] = {
519 GIVEN_FIRST: "GIVEN_FIRST",
520 FAMILY_FIRST: "FAMILY_FIRST",
521 FAMILY_FIRST_GIVEN_LAST: "FAMILY_FIRST_GIVEN_LAST",
522}
525def _order_repr(value: tuple[Role, ...]) -> str:
526 # Unreachable via Policy's constructor (its __post_init__ restricts
527 # name_order to the three named orders) but REACHABLE via
528 # PolicyPatch, which defers name_order validation to apply time by
529 # design -- value may hold non-Role, even unhashable, elements. A
530 # value smuggled in through __setstate__ (which validates layout,
531 # not values) can also be a non-tuple container or not iterable at
532 # all. repr must never raise, so the named-lookup path is taken
533 # only for a TUPLE whose every element is confirmed a Role;
534 # everything else renders via repr(value). (The annotation states
535 # the Policy-side truth; the PolicyPatch call site passes
536 # getattr-Any.)
537 if isinstance(value, tuple) and all(isinstance(r, Role) for r in value):
538 named = _ORDER_CONSTANT_NAMES.get(value)
539 if named is not None:
540 return named
541 return "(" + ", ".join(r.name for r in value) + ")"
542 return repr(value)
545def _fields_repr(obj: Policy | PolicyPatch, name: str,
546 skip: Callable[[dataclasses.Field[Any], object], bool]) -> str:
547 """`name(...)` over every field of `obj` that `skip` does not drop,
548 name_order through _order_repr: the one body Policy's and
549 PolicyPatch's bounded reprs share, so a field needing its own repr
550 is written once."""
551 parts = []
552 for f in dataclasses.fields(obj):
553 value = getattr(obj, f.name)
554 if skip(f, value):
555 continue
556 if f.name == "name_order":
557 parts.append(f"name_order={_order_repr(value)}")
558 else:
559 parts.append(f"{f.name}={value!r}")
560 return f"{name}({', '.join(parts)})"
563# Single source for the migration hint raised by both Policy and
564# PolicyPatch when patronymic_rules gets a non-iterable (True is the
565# likeliest wrong value -- v1's flag was a bool that enabled BOTH rules).
566_PATRONYMIC_MIGRATION_HINT = (
567 "v1's patronymic_name_order=True enabled both rules -- "
568 "patronymic_rules={PatronymicRule.EAST_SLAVIC, "
569 "PatronymicRule.TURKIC} (or pick one via "
570 "parser_for(locales.RU) / locales.TR_AZ)"
571)
573#: Policy.script_orders' default: wholly-Han, wholly-Hangul, and
574#: kana-licensed names read family-first. Public and named so opting
575#: out or extending reads against a documented value (the
576#: DEFAULT_NICKNAME_DELIMITERS precedent). The HAN entry is safe
577#: WITHOUT knowing Chinese from Japanese: both write family-first in
578#: native script -- the languages differ, the convention doesn't.
579#: HIRAGANA joins by the same rule as HANGUL (the kana license,
580#: amendment 2026-07-29): a mixed Han-and-kana token cannot be
581#: Chinese (it contains kana) and is not a foreign transcription
582#: (transcriptions are katakana-only), so it is Japanese, written
583#: family-first -- another default change in a minor, release-log-
584#: classified fix, #294's mechanism. KATAKANA is deliberately absent:
585#: a PURE-katakana token may be a transcribed foreign name kept in its
586#: source (usually given-first) order, or a Japanese reading written
587#: family-first -- legacy halfwidth data (#594) spells Japanese names in
588#: katakana too -- and the script cannot tell them apart, so nothing should
589#: default on it. Canonical form: sorted (Script, order) pairs,
590#: matching the field's storage.
591DEFAULT_SCRIPT_ORDERS: tuple[
592 tuple[Script, tuple[Role, Role, Role]], ...] = (
593 (Script.HAN, FAMILY_FIRST),
594 (Script.HANGUL, FAMILY_FIRST),
595 (Script.HIRAGANA, FAMILY_FIRST),
596)
598#: Policy.nickname_delimiters' default. Public and named so
599#: customizations read as set math against a documented value -- e.g.
600#: ``DEFAULT_NICKNAME_DELIMITERS | {("⦅", "⦆")}`` -- instead of a
601#: rebuilt literal the user had to go discover. The v1 trio (straight
602#: quotes + parentheses) plus the typographic conventions (#273):
603#: smart quotes, low-high and right-right quotes, guillemets both
604#: directions, CJK corner brackets (full-width and the halfwidth
605#: 「」 legacy JIS X 0201 data carries, #597), fullwidth parentheses.
606#: Curly SINGLE quotes are deliberately absent: U+2019 is the
607#: typographic apostrophe ("O’Connor").
608DEFAULT_NICKNAME_DELIMITERS = frozenset({
609 ("'", "'"), ('"', '"'), ("(", ")"), # v1 trio
610 ("“", "”"), # smart quotes (en, zh)
611 ("„", "“"), # low-high (de, pl, cs, hu)
612 ("”", "”"), # right-right (sv, fi)
613 ("«", "»"), # guillemets (fr, ru, it, el)
614 ("»", "«"), # reversed guillemets (de alt)
615 ("「", "」"), ("『", "』"), # CJK corner brackets (ja)
616 ("「", "」"), # halfwidth corner brackets
617 ("(", ")"), # fullwidth parentheses (CJK)
618})
621def _reject_str_and_mapping(value: object, field_name: str) -> None:
622 """The two shapes that iterate into something plausible but wrong.
624 A bare string yields its characters (and '' yields nothing at all,
625 so it silently stored an empty set); a Mapping yields only its keys.
626 Both used to be accepted here, storing a value the caller never
627 wrote. Lexicon._normset rejects the same two by name -- the wording
628 is deliberately parallel, since a caller who hits one field's guard
629 should recognize the other's.
630 """
631 if isinstance(value, str):
632 raise TypeError(
633 f"{field_name} must be an iterable, not a bare string: "
634 f"{value!r}"
635 )
636 # bytes iterate to ints, so the entry check would report a byte
637 # value and name neither the cause nor the fix; same decode hint
638 # Lexicon and parse() give.
639 if isinstance(value, (bytes, bytearray, memoryview)):
640 raise TypeError(
641 f"{field_name} must be an iterable of strings, not "
642 f"{type(value).__name__} -- decode first, e.g. "
643 f"raw.decode('utf-8')"
644 )
645 if isinstance(value, Mapping):
646 # Name the way out, not just the harm. "contributes only its
647 # keys" is no help for the two mappings people actually pass:
648 # {} (meant as an empty set -- Python's oldest trap, and the
649 # keys story does not apply because there are none), and an
650 # {open: close} dict, whose keys are only half the pair.
651 raise TypeError(
652 f"{field_name} must be an iterable, not a mapping: "
653 f"{value!r}. A mapping yields only its keys -- write "
654 f"frozenset() for an empty set, or .items() if this is an "
655 f"{{open: close}} pair mapping"
656 )
659def _validated_script(key: object) -> Script:
660 """Coerce one Script key, with the message every script-keyed field
661 shares. Single-sourced deliberately: script_orders and the
662 script-keyed fields that follow it must not each grow their own
663 wording for the same lookup."""
664 return _coerce_enum(key, Script, "script", "scripts")
667def _validated_script_orders(
668 value: object) -> tuple[tuple[Script, tuple[Role, Role, Role]], ...]:
669 """Policy.script_orders' whole check, from raw input to canonical
670 storage. script_orders is the one MAPPING-shaped field, so the
671 guards read inverted from every other one here: a Mapping is what
672 the caller SHOULD pass, and a bare string is the shape that would
673 otherwise iterate into plausible-looking garbage."""
674 if isinstance(value, str):
675 raise TypeError(
676 f"script_orders must be a mapping of Script to order, "
677 f"not a bare string: {value!r}"
678 )
679 if isinstance(value, (bytes, bytearray, memoryview)):
680 raise TypeError(
681 f"script_orders must be a mapping of Script to order, "
682 f"not {type(value).__name__} -- decode first, "
683 f"e.g. raw.decode('utf-8')"
684 )
685 raw = value.items() if isinstance(value, Mapping) else value
686 raw_iter = _require_iterable(
687 raw, "script_orders", # type: ignore[arg-type]
688 "a mapping of Script to order")
689 canonical: dict[Script, tuple[Role, Role, Role]] = {}
690 for entry in raw_iter:
691 try:
692 key, order = entry
693 except (TypeError, ValueError):
694 raise TypeError(
695 f"script_orders entries must be (Script, order) "
696 f"pairs, got {entry!r}"
697 ) from None
698 canonical[_validated_script(key)] = _validated_order(
699 order, "script_orders")
700 # Sorted pairs, not a dict: Policy is hashable, and two
701 # differently-written but equivalent tables must converge (the
702 # capitalization_exceptions precedent).
703 return tuple(sorted(canonical.items()))
706def _validated_segment_scripts(value: object) -> frozenset[Script]:
707 """segment_scripts' check: an iterable of Script members (or
708 their string values), coerced via _validated_script so the
709 unknown-script wording stays single-sourced."""
710 _reject_str_and_mapping(value, "segment_scripts")
711 script_iter = _require_iterable(
712 value, "segment_scripts", # type: ignore[arg-type]
713 "an iterable of Script members")
714 return frozenset(_validated_script(s) for s in script_iter)
717def _canonical_script_pair(pair: Iterable[Any]) -> tuple[Any, ...]:
718 """Hashability-only canonicalization of one PolicyPatch
719 script_orders entry: tuple-ize the pair AND the order value inside
720 it. Shallow was not enough -- a {Script: [Role, ...]} patch stored
721 the list, and hash() then raised far from the construction site,
722 the same failure name_order's canonicalization exists to prevent.
723 A malformed entry is still tuple-ized (that is the hashability
724 floor); its CONTENTS are left exactly as written so Policy quotes
725 the caller's own value when it raises at apply time."""
726 out = tuple(pair)
727 if len(out) != 2:
728 return out # not a (Script, order) pair
729 key, value = out
730 # str/bytes are iterable, so tuple() would shred exactly the two
731 # values whose deferred errors ("not a bare string", the decode
732 # hint) need to quote what the caller wrote.
733 if isinstance(value, (str, bytes, bytearray, memoryview)):
734 return out
735 try:
736 return (key, tuple(value))
737 except TypeError:
738 return out # non-iterable order value
741def _canonical_patch_script_orders(value: object) -> object:
742 """Canonicalize a PolicyPatch.script_orders value for hashability
743 without validating it: malformed shapes are stored so Policy can
744 quote them at apply time; a caller-generator's own exception
745 propagates from the UNGUARDED materialization below (deferring is
746 impossible once a one-shot iterator is consumed)."""
747 # Excluded HERE rather than delegated: a string's elements are
748 # themselves tuple-izable, so no TypeError ever fires to signal
749 # "leave this alone" -- "han" would shred to (("h",), ("a",),
750 # ("n",)) and Policy's bare-string message would have nothing left
751 # to quote. bytes shred the same way, into ints.
752 if isinstance(value, (str, bytes, bytearray, memoryview)):
753 return value # deferred whole: Policy's guards quote it
754 # Any, not object: a patch defers validation, so anything a caller
755 # wrote can arrive here, and the probe below is precisely the
756 # runtime question mypy has no way to answer statically.
757 pairs: Any = value.items() if isinstance(value, Mapping) else value
758 try:
759 pairs_iter = iter(pairs) # probe only
760 except TypeError:
761 return value # non-iterable: defer to apply
762 items = tuple(pairs_iter) # UNGUARDED: caller errors propagate
763 try:
764 return tuple(map(_canonical_script_pair, items))
765 except TypeError:
766 return items # malformed entry: materialized, so
767 # Policy can still re-iterate + quote
770@dataclass(frozen=True, slots=True)
771class Policy:
772 """The behavior switches a parser runs with: name order,
773 patronymic rules, delimiter routing, input scrubbing. Immutable
774 and hashable; every field has a safe default, so construct with
775 only what you change -- ``Policy(maiden_delimiters=frozenset({("(", ")")}))``
776 -- and pass the result to ``Parser(policy=...)``."""
778 #: How positional (no-comma) input maps onto given/middle/family
779 #: (a name of one name word is placed by lone_name_word instead).
780 #: Valid values are exactly the three exported
781 #: :ref:`name-order constants <name-order-constants>` --
782 #: GIVEN_FIRST (the default), FAMILY_FIRST, and
783 #: FAMILY_FIRST_GIVEN_LAST; any other tuple of Roles raises
784 #: ValueError. Ignored when a comma separates family from given:
785 #: "Thomas, John" puts the family name first no matter which words
786 #: could otherwise be either ("Thomas" and "John" both work as
787 #: given or family names). A comma that only sets off suffixes
788 #: ("John Smith, Jr.") leaves name_order governing the name part.
789 name_order: tuple[Role, Role, Role] = GIVEN_FIRST
790 #: Per-script overrides of name_order (#271), consulted when every
791 #: name piece is written wholly in one script, or in the
792 #: Han/Hiragana/Katakana repertoire the #272 kana license shares
793 #: across pieces: {Script: order} (constructor accepts a mapping;
794 #: stored as sorted pairs). The default reads wholly-Han/Hangul
795 #: names, and kana-licensed Japanese names, family-first -- see
796 #: :data:`~nameparser.DEFAULT_SCRIPT_ORDERS`. Opt out with
797 #: ``script_orders=()``. Latin-script and mixed-script input is
798 #: never affected. Like name_order, ignored where a comma already
799 #: decides the family name.
800 script_orders: tuple[tuple[Script, tuple[Role, Role, Role]], ...] = (
801 DEFAULT_SCRIPT_ORDERS)
802 #: Scripts for which the unspaced-name segmentation stage is
803 #: active (#271): the first token written wholly in an activated
804 #: script is split by longest surname match against
805 #: :attr:`Lexicon.surnames <nameparser.Lexicon.surnames>`, and,
806 #: where that vocabulary declines, by a
807 #: :data:`~nameparser.Segmenter` if one was given to the parser
808 #: (#272). Default: {Script.HANGUL} -- hangul is unambiguously
809 #: Korean and Korean surnames are a closed default-shipped set.
810 #: Han is NOT default: a zh surname list corrupts Japanese names
811 #: (高橋一郎 must not split as 高+橋一郎), so it's opt-in via
812 #: locales.ZH for Chinese and locales.JA -- which activates
813 #: Script.HIRAGANA alongside it, the kana license's carrier key --
814 #: for Japanese.
815 #: Only the East Asian members divide anything: Script.CYRILLIC keys
816 #: a declared order alone, and listed here it is inert.
817 #: Opt out with ``segment_scripts=frozenset()``; note a PolicyPatch unions
818 #: rather than replaces, so a pack can only add scripts, never
819 #: disable one.
820 segment_scripts: frozenset[Script] = frozenset({Script.HANGUL})
821 #: Opt-in detectors that reorder patronymic-shaped names
822 #: (EAST_SLAVIC, TURKIC); usually set via a locale pack. A rotation
823 #: restores the given-first reading a family-first listing hides, so
824 #: under a declared FAMILY_FIRST or FAMILY_FIRST_GIVEN_LAST name_order
825 #: it stands down and the declaration decides.
826 patronymic_rules: frozenset[PatronymicRule] = frozenset()
827 #: Folds middle into family instead of splitting them (v1's
828 #: middle_name_as_last) -- for data where unrecognized interior
829 #: words are surname parts, not middle names: multi-part surnames
830 #: like Spanish/Portuguese dual surnames ("Gabriel García Márquez"
831 #: -> family "García Márquez" instead of middle "García").
832 middle_as_family: bool = False # v1's middle_name_as_last
833 #: (open, close) pairs whose enclosed content becomes the nickname
834 #: field. Defaults to
835 #: :data:`~nameparser.DEFAULT_NICKNAME_DELIMITERS` (#273).
836 nickname_delimiters: frozenset[tuple[str, str]] = DEFAULT_NICKNAME_DELIMITERS
837 #: (open, close) pairs whose enclosed content becomes the maiden
838 #: field instead; a pair listed here is dropped from the effective
839 #: nickname set (maiden wins, see __post_init__), so
840 #: maiden_delimiters=frozenset({("(", ")")}) is the whole recipe (#274).
841 #: Set this for a clause that says nothing about itself, which is
842 #: two kinds and not one: content with no marker word in it, and a
843 #: LONE marker word. Since #335 a clause that opens with a marker
844 #: word AND has a word after it reads as the maiden name whatever
845 #: pair encloses it, so "Jane Smith (née Jones)" needs no
846 #: configuration -- unless S1 takes the clause first: a clause of
847 #: credentials, generations or titles is set apart from the name,
848 #: and other content ending in a period loses its brackets and is
849 #: read as if written bare. A maiden_markers entry opening the enclosed
850 #: content is dropped from the value -- all of it, an entry being
851 #: allowed to span more than one word ("z domu") -- but only where
852 #: a word stands past it: a clause of nothing but its marker keeps
853 #: its words, since a lone "(Nee)" is a maiden NAME and not a
854 #: marker (#329).
855 maiden_delimiters: frozenset[tuple[str, str]] = frozenset()
856 #: Additional separators that split suffix groups (e.g. " | " for
857 #: "Jane Smith, RN | CRNA"). Additive only: the comma, the
858 #: semicolon, and a hyphen or slash standing alone split suffix
859 #: groups after a whole name and cannot be replaced -- comma handling is
860 #: structural (the same comma reading that parses "Family, Given"
861 #: input), not a configurable delimiter, the semicolon is built in
862 #: since 2.6 and the spaced hyphen and slash since 2.7 (rules/C10).
863 #: A declared separator glued to a suffix word after the first comma
864 #: counts too, as the semicolon does: "John Smith, MD; PhD" reads
865 #: suffix "MD; PhD", the word keeping its separator. The built-in
866 #: hyphen and slash do not count glued, being a word's own there
867 #: ("al-", "MD/PhD"); declaring " - " makes the hyphen count glued.
868 extra_suffix_delimiters: frozenset[str] = frozenset()
869 #: Governs "Family, Suffix"-shaped input where the suffix word is
870 #: also initial-shaped (a single letter, bare or period-written --
871 #: of the default vocabulary that means the roman numerals "I" and
872 #: "V"): "John Smith, V" reads as John Smith the fifth when True
873 #: (the default, v1 behavior); False reads "V" as a given-name
874 #: initial instead (family "John Smith", given "V"), and "john
875 #: smith, v" the same way, a name written in one case reading as
876 #: its capitals (rules/T4). Multi-letter suffixes ("III", "MD")
877 #: parse the same either way.
878 lenient_comma_suffixes: bool = True
879 #: Excludes emoji from tokenization: they appear in no token,
880 #: field, or rendered view. The original string keeps them (input
881 #: is never modified -- spans stay true).
882 strip_emoji: bool = True
883 #: Excludes bidirectional control characters from tokenization:
884 #: they appear in no token, field, or rendered view; the original
885 #: string keeps them.
886 strip_bidi: bool = True # =False replaces 1.x's opt-out CONSTANTS.regexes.bidi = False
887 # -- fields added after 2.3 ------------------------------------------
888 # Policy is not kw_only, so a field's POSITION is API: a caller
889 # writing Policy(GIVEN_FIRST, ..., True, False) binds by position.
890 # The two 2.4 switches below first landed beside
891 # lenient_comma_suffixes, which re-bound every positional argument
892 # from `strip_emoji` on; they are appended here instead so 2.3's
893 # eleven positions keep their meaning
894 # (tests/v2/test_policy.py::test_the_2_3_positional_fields_did_not_move).
895 # A field added in a later cycle goes at the END for the same
896 # reason, whatever it is about.
897 #: Reads an UNLISTED token of two or more period-separated chunks
898 #: as a credential where the position allows it: "John Smith
899 #: X.Y.Z." gives suffix ``X.Y.Z.`` and "Jack X.Y.Z." keeps family
900 #: ``X.Y.Z.``, the same words-to-spare rule a listed ambiguous
901 #: acronym takes, and either reading is reported. Case is
902 #: irrelevant here -- the periods are the signal, so
903 #: "john smith x.y.z." reads as the mixed-case spelling does.
904 #: Whole-token vocabulary still wins ("M.A.", "Ph.D.", "A.B.C."),
905 #: and a single trailing period is not this shape ("John Smith
906 #: Xyz." keeps family ``Xyz.``), and nor are paired initials, two
907 #: single letters each followed by a period in a script with
908 #: capitals ("Ram Bahadur B.K." keeps family ``B.K.``) except
909 #: right after a comma, where they are the given name unless
910 #: something in the part speaks for them, or a listed credential in
911 #: a later comma part where they stand alone in theirs ("Jane Doe,
912 #: B.M., PhD" gives suffix ``B.M., PhD``). ``False`` reads such a token as
913 #: name material everywhere, as 2.3 did for a token no chunk
914 #: claimed; the roman-chunk retirement (rules/S3) is not
915 #: behind this switch, and still reports the fork.
916 unlisted_dotted_suffixes: bool = True
917 #: Where an UNLISTED all-caps word of two or more letters, with no
918 #: period in it, reads as a credential (:class:`CapsSuffixes`). The
919 #: name must contrast it: a word of the name holding a capital whose
920 #: last letter is lowercase ("Smith", "DiCaprio") that the
921 #: vocabulary does not claim as a title, particle
922 #: or credential -- a record written wholly in capitals or wholly in
923 #: lowercase keeps every word a name word. A listed member keeps its
924 #: own case lean in every setting ("Jack MA" gives suffix ``MA``),
925 #: and the roman-numeral fork claims a bare numeral first ("Jack
926 #: VI" is unaffected).
927 #:
928 #: ``AFTER_COMMA``, the default, reads it only in the part after a
929 #: comma with two or more name words before it: "John Smith, XYZ"
930 #: gives suffix ``XYZ``, while "Smith, XYZ" keeps given ``XYZ`` (one
931 #: name word). There a word in mixed case that opens with two
932 #: capitals or ends in one is read as an all-caps word is ("Jane
933 #: Smith, MRes", "Jane Smith, AuD"), a capital only inside a word
934 #: being a name's writing ("Jane Smith, LeBron" keeps given
935 #: ``LeBron``). "García Márquez, MJ" keeps given ``MJ`` -- a lone
936 #: two-letter word is how a person's initials are written, and two
937 #: words before the comma may be one surname, the case #563 decides
938 #: for "M.J." too. Credentials behind the two letters make them one:
939 #: in their own part ("Jane Doe, BM PhD"), or a listed credential
940 #: in a later comma part where they stand alone in theirs ("Jane
941 #: Doe, BM, PhD"; "Jane Doe, B.M., PhD" too, which
942 #: ``unlisted_dotted_suffixes`` governs). The all-caps SURNAME
943 #: convention ("Jean DUPONT",
944 #: "DUPONT, Jean") writes the capitals at the end of a name or
945 #: before a comma, never after one behind a full name, which is why
946 #: this position is on by default and the others are not.
947 #:
948 #: ``EVERYWHERE`` adds the end of a name with no comma, the
949 #: convention's own position: "John Smith XYZ" gives suffix ``XYZ``,
950 #: and "Jean Pierre DUPONT" gives family ``Pierre``, suffix
951 #: ``DUPONT`` -- the cost, a swallowed family name being the worse
952 #: failure. The mixed-case word is not read there: "Alex Lee ONeill"
953 #: keeps family ``ONeill``. The two-word "Jean DUPONT" and "Minjun KIM" keep their
954 #: family even then (one word before the credential is never
955 #: enough), but gain the fork's report. ``OFF`` reads no such word
956 #: as a credential anywhere and reports nothing, as 2.3 did. A digit
957 #: disqualifies the token and a single capital stays an initial.
958 #: ``isupper()`` is script-agnostic, so the same holds in any script
959 #: with a case contrast ("Иван ИВАНОВ", "Jean ÉCOLE").
960 unlisted_caps_suffixes: CapsSuffixes = CapsSuffixes.AFTER_COMMA
961 #: Reads the last two name words of a name as the family, for data
962 #: where a person carries two family names and writes both
963 #: (rules/O6): "Gabriel García Márquez" gives given ``Gabriel``,
964 #: family ``García Márquez``, and "Ana María García López" gives
965 #: middle ``María``, family ``García López``. A particle counts with
966 #: the word it attaches to ("Juan Pérez de la Vega" gives family
967 #: ``Pérez de la Vega``), a family already holding two words keeps
968 #: what it has ("José María Ortega y Gasset", "Ana María
969 #: García-López", "Ana María de la Vega Rodríguez"), and is divided
970 #: by its own words into ``surname1`` and ``surname2`` (``de la
971 #: Vega``, ``Rodríguez``) unless ``y`` joins it or it is one
972 #: hyphenated word, titles and
973 #: suffixes count as no name word, and a name of two name words is
974 #: unchanged. The word taken must be one name word a family name
975 #: could be, so an initial written alone ("Ana M. García"), hyphenated
976 #: initials ("Ana M.-J. López") and a bound given-name pair stay where
977 #: they are; a hyphenated word counts as one when
978 #: taken ("Andrés Sánchez-Cid Torres" gives family ``Sánchez-Cid
979 #: Torres``), so a hyphenated given name is taken unless every part
980 #: of it is a listed given name or an initial (``Lexicon.given_names``). Under a family-first
981 #: name_order the FIRST two name words are the family; a name its
982 #: script reads in an order other than name_order (a spaced Han or
983 #: Hangul name under the default) is left alone, though under a
984 #: declared FAMILY_FIRST, which the script agrees with, it moves. A
985 #: family comma decides by itself, so "García López, Ana" keeps its
986 #: family, divided into ``surname1`` ``García`` and ``surname2``
987 #: ``López`` as the comma-less name is. A name with one family name behind two given names
988 #: loses one to the family ("Juan Carlos Pérez" gives family
989 #: ``Carlos Pérez``), which is most English and Argentine names of
990 #: three words or more and many Portuguese and Brazilian ones as
991 #: filed: switched on for a mixed population it costs more names
992 #: than it mends, so it is off by default and reports nothing;
993 #: Parser.suggest may suggest it for a group written given name
994 #: first (Signal.FIRST_SURNAME). Runs before middle_as_family, which
995 #: then folds whatever middles are left.
996 two_family_names: bool = False
997 #: Reads the given name as two name units, for data where a person
998 #: carries a compound given name and no middle name (rules/O7):
999 #: "Juan Carlos Pérez" gives given ``Juan Carlos``, family
1000 #: ``Pérez``, and with ``two_family_names`` too, "María José García
1001 #: López" gives given ``María José``, family ``García López``. The
1002 #: middle unit beside the given name joins it -- the one after it,
1003 #: or the one before it under FAMILY_FIRST_GIVEN_LAST with no family
1004 #: comma, after which the part reads given-first -- and any
1005 #: middles past that stay middles; a particle chain the parse left
1006 #: in the middle counts with its word ("María del Carmen de la
1007 #: Vega" gives given ``María del Carmen``), and an initial is taken,
1008 #: a given name written short. A given name already holding two
1009 #: words keeps what it has (a hyphenated or bound pair), the word
1010 #: taken must be one name word, and a word an ending rule reads as a
1011 #: patronymic stays where it is. A family comma leaves the given part
1012 #: to this rule ("Pérez, Juan Carlos"); a name its script reads in an
1013 #: order other than name_order is left alone, as two_family_names
1014 #: leaves it. Runs after two_family_names, which takes its word
1015 #: first ("Gabriel García Márquez" keeps given ``Gabriel``), and
1016 #: before middle_as_family, which then folds whatever middles are
1017 #: left. A name whose second given word is a middle name gains it
1018 #: in the given name ("John Quincy Adams" gives given ``John
1019 #: Quincy``), so it is off by default and reports nothing. Added in
1020 #: 3.0.
1021 two_given_names: bool = field(
1022 default=False, metadata={ADDED_IN: "3.0.0"})
1023 #: The field a name of one name word reads that word as, when
1024 #: nothing else decides it (rules/O5): ``Role.GIVEN`` (the default)
1025 #: or ``Role.FAMILY``, under every name_order. "Anh" gives given
1026 #: ``Anh``; with ``lone_name_word=Role.FAMILY`` it gives family
1027 #: ``Anh``. Which field a word written alone fills is a fact about
1028 #: where the data came from -- a list of surnames, a list of the
1029 #: names people go by -- not about the order its longer names are
1030 #: written in, so it does not follow name_order. A title, a
1031 #: nickname, a maiden name, a family comma or a script that settles
1032 #: the order still decides first ("Mr. Johnson" gives family
1033 #: ``Johnson``). The reading is reported as a ``given-or-family``
1034 #: ambiguity either way, save a word its own reading claimed (a
1035 #: particle, a bound given name, an initial), which the switch
1036 #: places too and which reports nothing. Added in 3.0; through 2.x
1037 #: the field followed name_order.
1038 lone_name_word: Role = field(
1039 default=Role.GIVEN, metadata={ADDED_IN: "3.0.0"})
1040 #: Reads two or more single letters ending a name as its family
1041 #: name, for data written in the South Asian convention where the
1042 #: letters after the given name stand for the father's or the
1043 #: family's name (rules/O8): "Lakshmi R S" gives given ``Lakshmi``,
1044 #: family ``R S``, and "Ram Bahadur B K" gives given ``Ram``,
1045 #: middle ``Bahadur``, family ``B K``. The letters are written as
1046 #: initials are, a bare Latin capital or a letter and its period,
1047 #: spaced and in a row, with a name word before them; one
1048 #: letter, letters before the name or inside it, and the given part
1049 #: after a family comma are left alone, and so is a name read in a
1050 #: family-first order, which already places those letters. Off by
1051 #: default: the same shape is a middle and a family initial in many
1052 #: lists ("Melanie J D") and a byline written surname first in a
1053 #: bibliography ("Huntley R P", for which name_order=FAMILY_FIRST
1054 #: is the setting). locales.NE turns it on, and Parser.suggest
1055 #: suggests it for a group whose names repeat one run of letters.
1056 #: Added in 3.1.
1057 initials_as_family: bool = field(
1058 default=False, metadata={ADDED_IN: "3.1.0"})
1059 #: Reads the words a name writes in capitals as its family name,
1060 #: for data whose source writes every family name in capitals
1061 #: (rules/O9): "DUPONT Marie" gives given ``Marie``, family
1062 #: ``DUPONT``, "Ayla BURSALI AKSOY" gives family ``BURSALI AKSOY``,
1063 #: and "Jeffrey LAM Kin-fung" gives given ``Jeffrey``, middle
1064 #: ``Kin-fung``, family ``LAM``, wherever the capitals stand. The
1065 #: other words keep their written order, the first that may be a
1066 #: given name being the given name.
1067 #:
1068 #: A capitals word has two or more capital letters and nothing but
1069 #: letters, apostrophes and hyphens ("O'BRIEN" and "McDONALD"
1070 #: count, "DR.", "N/A" and "J-P" do not). Particles and
1071 #: conjunctions join a run, a run of particles alone is none, and
1072 #: where a name word divides two runs the last is the family. The
1073 #: capitals outrank a credential or title reading ("Hugo LAC",
1074 #: "DOYEN Hugo" give family ``LAC`` and ``DOYEN``), while a listed
1075 #: credential or numeral in capitals ending the name still comes off
1076 #: where a capitals word before it, no particle, conjunction,
1077 #: numeral or marker, is left to be the family ("Marie GRAJALES
1078 #: III", "DUPONT Marie MBA", but "Marie MA MBA" gives family
1079 #: ``MA``), and a marker the patronymic rule in force reads is no
1080 #: capitals word where another capitals word is left to be the
1081 #: family ("ALIYEV Ilham Heydar OGLU"), though one that is the only
1082 #: capitals word is the family ("ABRAMOVICH Roman").
1083 #:
1084 #: Only a name in mixed case is read, one where a word no run took,
1085 #: other than a title, a suffix, or a particle or conjunction
1086 #: written in lowercase, holds a lowercase letter ("MORRISON Van" is
1087 #: read, "MARIE de DUPONT" is not), and only the part before its
1088 #: first comma: after a family comma the comma, not the capitals,
1089 #: names the family.
1090 #:
1091 #: Off by default: in data that does not write the convention,
1092 #: capitals also write a given name ("ANNA Smith") or a credential
1093 #: ("John Smith MD"); where one of ORCID's two boxes is wholly in
1094 #: capitals it is the given box about one time in ten. Cannot be set with
1095 #: ``unlisted_caps_suffixes=CapsSuffixes.EVERYWHERE``, which reads
1096 #: the same unlisted word as a credential. Parser.suggest suggests it
1097 #: for a group whose names write the family in capitals. Added in 3.1.
1098 capitals_as_family: bool = field(
1099 default=False, metadata={ADDED_IN: "3.1.0"})
1101 # in the class body so @dataclass(slots=True) keeps them
1102 __getstate__ = _guarded_getstate
1103 __setstate__ = _guarded_setstate
1105 # rules/D2: "configuration validation raises at construction
1106 # with the offending field and value named"
1107 def __post_init__(self) -> None:
1108 object.__setattr__(
1109 self, "name_order", _validated_order(self.name_order,
1110 "name_order"))
1111 object.__setattr__(
1112 self, "script_orders",
1113 _validated_script_orders(self.script_orders))
1114 object.__setattr__(
1115 self, "segment_scripts",
1116 _validated_segment_scripts(self.segment_scripts))
1117 _reject_str_and_mapping(self.patronymic_rules, "patronymic_rules")
1118 # Probe with iter() rather than wrapping tuple(): non-iterables
1119 # (True especially -- v1's patronymic_name_order was a bool flag,
1120 # so it's the likeliest wrong value here) get the migration-
1121 # pointing message, while an exception raised inside a caller's
1122 # generator still propagates untouched from the tuple() below
1123 # instead of being rewritten. Only the enum lookup itself gets
1124 # the unknown-rule message, naming the offender.
1125 try:
1126 rule_iter = iter(self.patronymic_rules)
1127 except TypeError:
1128 raise TypeError(
1129 f"patronymic_rules must be an iterable of PatronymicRule "
1130 f"names, got {self.patronymic_rules!r}; "
1131 f"{_PATRONYMIC_MIGRATION_HINT}"
1132 ) from None
1133 items = tuple(rule_iter)
1134 object.__setattr__(self, "patronymic_rules", frozenset(
1135 _coerce_enum(r, PatronymicRule, "patronymic rule", "rules")
1136 for r in items))
1137 for pairs_name in ("nickname_delimiters", "maiden_delimiters"):
1138 _reject_str_and_mapping(getattr(self, pairs_name), pairs_name)
1139 pairs = tuple(_require_iterable(getattr(self, pairs_name), pairs_name))
1140 for pair in pairs:
1141 if (not isinstance(pair, tuple) or len(pair) != 2
1142 or not all(isinstance(s, str) for s in pair)):
1143 raise TypeError(
1144 f"{pairs_name} entries must be (open, close) tuples "
1145 f"of strings, got {pair!r}"
1146 )
1147 if not all(pair):
1148 raise ValueError(
1149 f"{pairs_name} entries must be pairs of non-empty "
1150 f"strings, got {pair!r}"
1151 )
1152 object.__setattr__(self, pairs_name, frozenset(pairs))
1153 # Maiden wins: a pair can route to exactly one field, and listing
1154 # it in maiden_delimiters is the specific intent, so the effective
1155 # nickname set drops it. Canonicalization, not validation (the
1156 # name_order coercion precedent): differently-written but
1157 # equivalent Policies converge to equal values.
1158 object.__setattr__(
1159 self, "nickname_delimiters",
1160 self.nickname_delimiters - self.maiden_delimiters)
1161 _reject_str_and_mapping(self.extra_suffix_delimiters,
1162 "extra_suffix_delimiters")
1163 delimiters = tuple(_require_iterable(
1164 self.extra_suffix_delimiters, "extra_suffix_delimiters"))
1165 for d in delimiters:
1166 if not isinstance(d, str):
1167 raise TypeError(
1168 f"extra_suffix_delimiters entries must be strings, "
1169 f"got {d!r}"
1170 )
1171 if not d:
1172 raise ValueError(
1173 "extra_suffix_delimiters entries must be non-empty strings"
1174 )
1175 object.__setattr__(
1176 self, "extra_suffix_delimiters", frozenset(delimiters)
1177 )
1178 # Truthy strings ("no", "false") would silently invert the
1179 # caller's intent downstream; bools are the one field kind the
1180 # coercing checks above can't cover.
1181 #
1182 # The roster is DERIVED from the dataclass rather than written
1183 # out: a hand-written list is a second place to remember, and
1184 # the twin loop in tests/v2/test_policy.py proved it -- it still
1185 # named 2.3's four flags after 2.4 added two, so the new
1186 # switches shipped with no "must be a bool" coverage while the
1187 # library validated them. `bool` is the whole test: every
1188 # bool-annotated Policy field is a flag, and the annotation is
1189 # a plain string here because of `from __future__ import
1190 # annotations` (AGENTS.md's guard-the-whole-family rule).
1191 for flag in _BOOL_FIELDS:
1192 value = getattr(self, flag)
1193 if not isinstance(value, bool):
1194 raise TypeError(
1195 f"{flag} must be a bool, got {value!r}"
1196 )
1197 # A bool is the likeliest wrong value -- the sibling
1198 # unlisted_dotted_suffixes is one, and `True` is an `int` the
1199 # enum would read as no member -- so name every member.
1200 caps = self.unlisted_caps_suffixes
1201 if isinstance(caps, bool):
1202 raise TypeError(
1203 f"unlisted_caps_suffixes must be a CapsSuffixes, got "
1204 f"{caps!r}; use CapsSuffixes.OFF, CapsSuffixes.AFTER_COMMA "
1205 f"(the default) or CapsSuffixes.EVERYWHERE")
1206 object.__setattr__(self, "unlisted_caps_suffixes", _coerce_enum(
1207 caps, CapsSuffixes, "unlisted_caps_suffixes value",
1208 "values"))
1209 # rules/O9: "the switch cannot be set with an unlisted capitals
1210 # word read as a credential everywhere" -- the two read the same
1211 # word ending a name with no comma opposite ways (#659)
1212 if (self.capitals_as_family
1213 and self.unlisted_caps_suffixes is CapsSuffixes.EVERYWHERE):
1214 raise ValueError(
1215 "capitals_as_family=True cannot be set with "
1216 "unlisted_caps_suffixes=CapsSuffixes.EVERYWHERE: the first "
1217 "reads an unlisted word in capitals ending a name as the "
1218 "family, the second reads it as a credential. Keep one: "
1219 "leave capitals_as_family False, or set "
1220 "unlisted_caps_suffixes to CapsSuffixes.AFTER_COMMA or "
1221 "CapsSuffixes.OFF, e.g. Policy(capitals_as_family=True, "
1222 "unlisted_caps_suffixes=CapsSuffixes.AFTER_COMMA)")
1223 lone = self.lone_name_word
1224 if not isinstance(lone, str):
1225 raise TypeError(
1226 f"lone_name_word must be a Role, got {lone!r}; use "
1227 f"Role.GIVEN (the default) or Role.FAMILY")
1228 if lone not in _LONE_NAME_WORD_ROLES:
1229 raise ValueError(
1230 f"lone_name_word must be Role.GIVEN or Role.FAMILY, got "
1231 f"{lone!r}: a name of one word is read as a given or a "
1232 f"family name")
1233 object.__setattr__(self, "lone_name_word", Role(lone))
1235 def __repr__(self) -> str:
1236 # Bounded: only fields that deviate from the default are shown
1237 # (design rule, see nameparser._types module docstring).
1238 return _fields_repr(self, "Policy",
1239 lambda f, value: value == f.default)
1241 # -- editing ------------------------------------------------------
1243 def patched(self, patch: PolicyPatch) -> Policy:
1244 """Fold a :class:`PolicyPatch` onto this Policy and return the
1245 combined Policy. Set-valued fields union with the patch's;
1246 script_orders merges by script, the patch's entries replacing
1247 the base's for their scripts; scalar fields are overridden by
1248 the patch; UNSET fields are
1249 left alone. Patch VALUES are validated here (Policy's
1250 constructor re-runs on the result), not at patch construction
1251 -- see PolicyPatch. The maiden-wins canonicalization applies
1252 to the combined result exactly as if it had been constructed
1253 directly."""
1254 if not isinstance(patch, PolicyPatch):
1255 raise TypeError(f"patched() takes a PolicyPatch, got {patch!r}")
1256 return apply_patch(self, patch)
1259#: Every bool-valued Policy field, read off the dataclass rather than
1260#: listed: `__post_init__`'s bool check sweeps this, so a flag added to
1261#: the class above is validated the day it lands and cannot ship
1262#: unchecked the way `unlisted_dotted_suffixes` and the then-bool
1263#: `unlisted_caps_suffixes` did. `from __future__ import annotations`
1264#: makes every annotation a string, so the comparison is against the
1265#: SPELLING "bool" -- which is also what a reader of the class body
1266#: sees, and a field annotated any other way is not a plain flag.
1267_BOOL_FIELDS: tuple[str, ...] = tuple(
1268 f.name for f in dataclasses.fields(Policy) if f.type == "bool")
1270#: The two fields `Policy.lone_name_word` may name (rules/O5).
1271_LONE_NAME_WORD_ROLES = frozenset({Role.GIVEN, Role.FAMILY})
1274class _Unset(Enum):
1275 UNSET = auto()
1278#: Sentinel for "this patch does not set this field" (picklable enum
1279#: member, distinguishable from every real value including None/False).
1280UNSET = _Unset.UNSET
1282_UNION = {"compose": "union"} # field metadata: set-valued -> union
1283_BY_SCRIPT = {"compose": "by-script"} # field metadata: merge per script
1286@dataclass(frozen=True, slots=True)
1287class PolicyPatch:
1288 """A partial Policy: one field per Policy field, all defaulting to
1289 UNSET. Composition per field is DECLARED via metadata -- set-valued
1290 fields union, script_orders merges by script (a patch's entry
1291 replaces the base's entry for its script, the rest standing), and
1292 scalars override (later wins). Kept in lockstep with
1293 Policy by the parity test in tests/v2/test_policy.py.
1295 Values are validated when the patch is applied (Policy's constructor
1296 re-runs), not at patch construction.
1297 """
1299 name_order: tuple[Role, Role, Role] | _Unset = UNSET
1300 #: Composes BY SCRIPT: each entry replaces the base's entry for its
1301 #: script and the base's other entries stand, so a pack adds one
1302 #: script's order without restating or erasing the rest, a caller's
1303 #: own opt-outs included (locales.MN's Cyrillic entry; decisions/W4,
1304 #: #1237).
1305 script_orders: tuple[
1306 tuple[Script, tuple[Role, Role, Role]], ...] | _Unset = field(
1307 default=UNSET, metadata=_BY_SCRIPT)
1308 segment_scripts: frozenset[Script] | _Unset = field(
1309 default=UNSET, metadata=_UNION)
1310 patronymic_rules: frozenset[PatronymicRule] | _Unset = field(
1311 default=UNSET, metadata=_UNION)
1312 middle_as_family: bool | _Unset = UNSET
1313 nickname_delimiters: frozenset[tuple[str, str]] | _Unset = field(
1314 default=UNSET, metadata=_UNION)
1315 maiden_delimiters: frozenset[tuple[str, str]] | _Unset = field(
1316 default=UNSET, metadata=_UNION)
1317 extra_suffix_delimiters: frozenset[str] | _Unset = field(
1318 default=UNSET, metadata=_UNION)
1319 lenient_comma_suffixes: bool | _Unset = UNSET
1320 strip_emoji: bool | _Unset = UNSET
1321 strip_bidi: bool | _Unset = UNSET
1322 # Appended, in Policy's order and for Policy's reason -- this class
1323 # is positional too, and the parity test holds the two field
1324 # sequences equal, so a field inserted on one side would have to be
1325 # inserted on the other and both would re-bind together.
1326 unlisted_dotted_suffixes: bool | _Unset = UNSET
1327 unlisted_caps_suffixes: CapsSuffixes | _Unset = UNSET
1328 two_family_names: bool | _Unset = UNSET
1329 #: Patches :attr:`Policy.two_given_names`, a scalar (later wins).
1330 #: Added in 3.0.
1331 two_given_names: bool | _Unset = field(
1332 default=UNSET, metadata={ADDED_IN: "3.0.0"})
1333 #: Patches :attr:`Policy.lone_name_word`, a scalar (later wins).
1334 #: Added in 3.0.
1335 lone_name_word: Role | _Unset = field(
1336 default=UNSET, metadata={ADDED_IN: "3.0.0"})
1337 #: Patches :attr:`Policy.initials_as_family`, a scalar (later
1338 #: wins). Added in 3.1.
1339 initials_as_family: bool | _Unset = field(
1340 default=UNSET, metadata={ADDED_IN: "3.1.0"})
1341 #: Patches :attr:`Policy.capitals_as_family`, a scalar (later
1342 #: wins). Added in 3.1.
1343 capitals_as_family: bool | _Unset = field(
1344 default=UNSET, metadata={ADDED_IN: "3.1.0"})
1346 # in the class body so @dataclass(slots=True) keeps them
1347 __getstate__ = _guarded_getstate
1348 __setstate__ = _guarded_setstate
1350 def __post_init__(self) -> None:
1351 # Canonicalize (but do NOT validate) collection fields so a patch
1352 # built from a set/list literal is hashable and unions cleanly in
1353 # apply_patch. name_order needs the same treatment: Policy would
1354 # coerce a list at apply time, but the patch itself (and any
1355 # Locale holding it) must already be hashable.
1356 if self.name_order is not UNSET:
1357 _reject_bare_string_order(self.name_order, "name_order")
1358 object.__setattr__(self, "name_order", tuple(self.name_order))
1359 # Same reason for script_orders, one level deeper: a patch built
1360 # from a {Script: order} dict (or a list of pairs) must already
1361 # be hashable, since a Locale holds it -- and hashable all the
1362 # way down, hence _canonical_script_pair. Validation still
1363 # belongs to Policy at apply time, so a shape the canonicalizer
1364 # cannot digest is left for it to report; the one-shot and
1365 # malformed-entry cases are _canonical_patch_script_orders'.
1366 if self.script_orders is not UNSET:
1367 object.__setattr__(
1368 self, "script_orders",
1369 _canonical_patch_script_orders(self.script_orders))
1370 for f in dataclasses.fields(self):
1371 if f.metadata.get("compose") != "union":
1372 continue
1373 value = getattr(self, f.name)
1374 if value is UNSET:
1375 continue
1376 # Shared with Policy, not re-implemented: this used to be an
1377 # inline copy of the bare-string half only, so the mapping
1378 # half never reached a patch -- and frozenset() below
1379 # destroys the evidence, leaving nothing for Policy to catch
1380 # at apply time. A Locale pack ships one of these.
1381 _reject_str_and_mapping(value, f.name)
1382 # same iter() probe as Policy: curated message for
1383 # non-iterables (with the v1-flag hint where it applies),
1384 # caller-generator exceptions propagate from frozenset()
1385 try:
1386 iter(value)
1387 except TypeError:
1388 hint = ("; " + _PATRONYMIC_MIGRATION_HINT
1389 if f.name == "patronymic_rules" else "")
1390 raise TypeError(
1391 f"{f.name} must be an iterable, got {value!r}{hint}"
1392 ) from None
1393 object.__setattr__(self, f.name, frozenset(value))
1394 # Every other field (the scalars: the bools,
1395 # unlisted_caps_suffixes and lone_name_word) DELIBERATELY gets no type check here,
1396 # unlike name_order and the union fields above: a
1397 # PolicyPatch(strip_emoji="off") is constructible, and only raises
1398 # once apply_patch runs Policy.__post_init__'s checks. This is
1399 # the one place the module's eager-validation ethos doesn't apply
1400 # -- see the class docstring ("Values are validated when the patch
1401 # is applied... not at patch construction").
1403 def __repr__(self) -> str:
1404 # Bounded: only fields the patch actually sets are shown; UNSET
1405 # fields are omitted (design rule, see nameparser._types module
1406 # docstring -- the sibling of Policy's deviation-only repr).
1407 return _fields_repr(self, "PolicyPatch",
1408 lambda f, value: value is UNSET)
1411def apply_patch(policy: Policy, patch: PolicyPatch) -> Policy:
1412 """Fold a PolicyPatch onto a Policy. Policy.__post_init__ re-runs via
1413 dataclasses.replace, so patched values are revalidated for free --
1414 including the maiden-wins canonicalization: a patch that adds a
1415 maiden pair removes that pair from the base's effective nickname
1416 set, exactly as if the combined Policy had been constructed
1417 directly. Intended (decided 2026-07-19): maiden_delimiters
1418 membership IS the routing decision, whoever contributes it."""
1419 updates: dict[str, object] = {}
1420 for f in dataclasses.fields(PolicyPatch):
1421 value = getattr(patch, f.name)
1422 if value is UNSET:
1423 continue
1424 if f.metadata.get("compose") == "union":
1425 value = getattr(policy, f.name) | value
1426 elif f.metadata.get("compose") == "by-script":
1427 # a well-formed table merges into the base's; anything else
1428 # (a bare string, an entry not a pair, an unhashable key)
1429 # goes to Policy whole, whose messages quote it
1430 try:
1431 value = {**dict(getattr(policy, f.name)), **dict(value)}
1432 except (TypeError, ValueError):
1433 pass
1434 updates[f.name] = value
1435 if not updates:
1436 return policy
1437 # Known mypy limitation with **dict-unpacked replace; see the full
1438 # explanation at Lexicon._edit in _lexicon.py.
1439 return dataclasses.replace(policy, **updates) # type: ignore[arg-type]