Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_lexicon.py: 23%

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

1059 statements  

1"""Immutable vocabulary configuration: a Lexicon holds readings, what 

2each word may be read as, and compiles the sets a parse reads from them 

3(3.0's 4i-b; decisions/vocabulary-model, 2026-11-02 #754). 

4 

5Layering: may import nameparser.config DATA modules as the single 

6source of vocabulary -- never the nameparser.config package itself -- 

7and nameparser._reading_index, the shared compiler and the index's 

8reader, at call time only: tools/vocab/build.py loads this module by 

9path. Enforced by tests/v2/test_layering.py. 

10""" 

11from __future__ import annotations 

12 

13import dataclasses 

14import functools 

15import itertools 

16import re 

17import sys 

18import unicodedata 

19import warnings 

20from collections import Counter 

21from collections.abc import Iterable, Mapping, Set 

22from dataclasses import dataclass, field 

23from types import FrameType, MappingProxyType, ModuleType 

24from typing import TYPE_CHECKING, Any, NamedTuple, cast 

25 

26#: Vocabulary set fields, in declaration order: the 2.x `Lexicon` 

27#: fields but the masks, and `given_names` (3.0). Since 3.0's 4i-b 

28#: (#754) only the two lists (`_LIST_FIELDS`) are still fields, the 

29#: rest being the sets a compile of readings gives (`_SET_FIELDS`); 

30#: add() and remove() take a word and its reading's kind, never one of 

31#: these names, and ``|`` unions the lists, concatenates the edit logs 

32#: (which is how every other set is joined) and merges 

33#: capitalization_exceptions right-biased. 

34_VOCAB_FIELDS = ( 

35 "titles", "given_name_titles", "suffix_acronyms", "suffix_words", 

36 "suffix_acronyms_ambiguous", "particles", "particles_ambiguous", 

37 "conjunctions", "conjunctions_ambiguous", "bound_given_names", 

38 "given_name_abbreviations", 

39 "maiden_markers", "surnames", "honorific_tails", "after_given_titles", 

40 "suffix_words_ambiguous", "agnomens", "titles_ambiguous", 

41 "title_modifiers", "title_styles", "title_phrases", "given_names", 

42) 

43 

44#: The metadata key a Lexicon field added after `Lexicon` first shipped 

45#: carries, naming the release that added it, with a default: a pickle 

46#: written before that release lacks the field and loads with the 

47#: default. The same string as `_types.ADDED_IN`, the key the other 

48#: frozen types' shared guard reads; layering keeps this module from 

49#: importing `_types`, so tests/v2/test_lexicon.py holds the two equal. 

50_ADDED_IN = "nameparser.added_in" 

51 

52#: Every character the parser reads as a full stop at a WORD'S EDGE 

53#: (#322/#323): the ASCII period, the fullwidth FULL STOP U+FF0E, the 

54#: IDEOGRAPHIC FULL STOP U+3002 and its halfwidth form U+FF61. One 

55#: string, four readers -- the lookup fold below, _vocab's script 

56#: classification fold, _script_segment's surname site and honorific 

57#: tail match -- so that "which characters are a period" is answered 

58#: once; the bundle's fifth site, _pieces' opening-abbreviation shape, 

59#: reads no stop set at all but the script-property table's 

60#: no-period-abbreviation spans (_policy._NO_ABBREVIATION_RANGES), the 

61#: repertoire that licenses every reader here. NFKC is 

62#: NOT a substitute for listing them: it folds U+FF0E to '.' and 

63#: U+FF61 to U+3002, and leaves U+3002 as it is. 

64#: Not every period test reads this set, and the ones that do not are 

65#: named so the claim is checkable: the interior-period shapes -- the 

66#: dotted acronym 'M.A.' and the split 'Ph. D.' (_vocab) -- and FOUR 

67#: ASCII-only edge tests on Latin shapes, across THREE modules -- the 

68#: initial 'J.' (_vocab), the bracketed credential '(Mgr.)' and the 

69#: word-internal apostrophe rule (_extract), and the trailing 

70#: middle-initial carve-out 'V.' (_assign) -- stay ASCII. That is a 

71#: fact about those TESTS and not about this set's reach: the fold 

72#: below is script-agnostic, so a LATIN word wearing a wide stop 

73#: reaches vocabulary the ASCII veto would have taken it out of. 

74#: 'V。' folds to 'v' and does not end in the ASCII period the 

75#: trailing-suffix carve-out tests (_assign, not is_initial), so 

76#: it is roman five -- suffix -- where 'V.' stays a middle 

77#: initial through that same carve-out; 'Jr。' simply reaches its 

78#: entry, and 'Dr。' its title. 

79#: decisions/cjk-full-stops carries the measurements. 

80FULL_STOPS = "..。。" 

81 

82 

83# The Arabic tatweel (kashida) stretches a word for looks and carries no 

84# letter, so deleting it changes no word's identity (#1151: `الدكتــور` 

85# is the title `الدكتور`). Token text is never rewritten. 

86_TATWEEL = "\u0640" 

87# rules/T1: "at the edge the word is looked up without it" 

88# The zero-width non-joiner and joiner shape the letters on either side 

89# of them, so at a word's edge they shape nothing and are dropped when 

90# the word is looked up, with the edge full stops (decisions/T1, 

91# #1335). Inside a word they stay 

92# (`آیت‌الله` is listed with its ZWNJ). Token text is never rewritten, 

93# which keeps the ZWJ Malayalam writes at a word's end. 

94_EDGE_JOINERS = "\u200c\u200d" 

95_NON_ASCII_EDGES = FULL_STOPS + _EDGE_JOINERS 

96 

97 

98def _a(kind: str) -> str: 

99 """The article a message writes before a reading's kind: ``an`` 

100 before a vowel and before ``honorific``, whose h is silent.""" 

101 return "an" if kind[:1] in "aeiou" or kind == "honorific" else "a" 

102 

103 

104def _normalize(word: str) -> str: 

105 """Lowercase, NFC-compose, strip whitespace and EDGE full stops 

106 (FULL_STOPS, not the ASCII period alone -- #322), and in a non-ASCII 

107 word an edge ZWNJ or ZWJ with them (#1335). Interior periods 

108 survive on purpose: 'J.R.' must not collapse to 'jr' and hit the 

109 periodless vocabulary (v1 parity, pinned live 2026-07-17). 

110 Suffix-ACRONYM membership alone uses the period-free form (see 

111 _vocab.suffix_as_written), mirroring v1's is_suffix, which removed 

112 periods only for the acronym test. 

113 

114 lower(), NOT casefold(): casefold's caseless-matching folds mutate 

115 the stored vocabulary itself -- 'κος' becomes the misspelling 'κοσ' 

116 (final sigma flattened) and 'großfürst' becomes 'grossfürst' -- 

117 while lower() applies Unicode SpecialCasing contextually and keeps 

118 both as authored. This function is the single fold for storage AND 

119 match-time lookups, so matching stays symmetric either way; lower() 

120 is what v1's lc() used, preserving which cross-spellings match. 

121 

122 Tatweel (U+0640) is deleted, in a non-ASCII word only (#1151). 

123 A ZWNJ or ZWJ at the word's edge is stripped with the edge full 

124 stops, in a non-ASCII word only (#1335); one inside the word stays. 

125 

126 NFC, since #322, and only for a non-ASCII word (ASCII is already 

127 NFC, and this runs per token on the parse path -- 

128 decisions/parse-cost). NFD hangul decomposes to jamo and missed 

129 every vocabulary entry; composing at lookup AND at storage keeps 

130 the two symmetric, and no shipped entry changes under it (measured 

131 2026-09-09: fold every string member of every Lexicon.default() 

132 field through NFC and count the changes; zero of 1735). This is 

133 the same NFC composition script classification already applies 

134 (_vocab._normalized_for_script); token text is never rewritten. 

135 

136 Strips to a FIXED POINT. A single strip().strip(FULL_STOPS) leaves 

137 stops-around-whitespace half done ('. a .' -> ' a '), so a value 

138 that is re-normalized later -- on unpickle, or by a second add() -- 

139 would change under its owner. v1 never re-normalized, so this only 

140 matters now that storage and match-time share one fold.""" 

141 word = word.lower() 

142 edges = FULL_STOPS 

143 if not word.isascii(): 

144 word = unicodedata.normalize("NFC", word) 

145 if _TATWEEL in word: 

146 word = word.replace(_TATWEEL, "") 

147 edges = _NON_ASCII_EDGES 

148 while True: 

149 stripped = word.strip().strip(edges) 

150 if stripped == word: 

151 return word 

152 word = stripped 

153 

154 

155# rules/P7: "A one-letter word written with its period is an 

156# initial and not a particle" 

157def _spells_an_initial(n: str, text: str) -> bool: 

158 """Whether `text` is ONE letter written with its period ('Ó.', 

159 'j.'), which makes it an initial whatever particle the letter also 

160 spells (#604). `n` is `_normalize(text)`, folded once by the caller. 

161 

162 Every particle test asks this AFTER its membership hit, so a word 

163 no particle set holds never pays the frame. It lives here rather 

164 than in _pipeline._vocab because _render's case repair, which 

165 re-reads the particle vocabulary over a parsed name, must ask it 

166 too and may not import the pipeline (the 2.x facade's initials and 

167 last-name split were a second such reader). 

168 

169 The ASCII period only, as `_vocab.is_initial` takes it: a CJK full 

170 stop marks no initial ('Ó。' is the particle). The other half of 

171 is_initial, the scripts that write no initials (#320), is NOT asked 

172 -- its script table is _policy's, which this module may not import 

173 -- so a caller's one-character particle in such a script, written 

174 with a period, is vetoed where is_initial would call it no initial 

175 (decisions/P7). No shipped particle is one character of those 

176 scripts.""" 

177 return len(n) == 1 and text[-1] == "." 

178 

179 

180def _fold_words(words: Iterable[str]) -> list[str]: 

181 """The words of a title run, folded for storage and lookup. 

182 

183 A multi-word title is matched as one key ('lt col'), so the fold has 

184 to run per word -- _normalize on the whole phrase would leave 

185 interior periods. 

186 

187 Words that fold away are DROPPED, not kept as empty. Keeping the 

188 gap makes the key non-idempotent -- 'lt .' would store 'lt ', which 

189 match time can never build: a run CAN carry a lone '.' (the 

190 conjunction merge puts one there), but the fold drops the empty 

191 word, so the key is 'lt' and the stored entry is inert. Storage 

192 re-runs this fold on unpickle and on every dataclasses.replace, so a 

193 value that changes under a second pass is one Lexicon later rejects as 

194 "not written by this version". _normalize converges for the same 

195 reason; so must anything built on top of it. 

196 

197 A LIST, so that _run_addresses_by_given's last-word arm can be the 

198 last word of this fold rather than a re-split of the joined key -- 

199 "the last word of the FOLDED key" is then structural, and the two 

200 arms read one fold between them. 

201 

202 map/filter rather than a comprehension: both are C calls where a 

203 comprehension is a Python frame on 3.11, and this runs on the parse 

204 path for every name carrying a title run (decisions/parse-cost). 

205 """ 

206 return list(filter(None, map(_normalize, words))) 

207 

208 

209def _title_key(words: Iterable[str]) -> str: 

210 """The given_name_titles lookup key for a run of title words: the 

211 folded words, space-joined. 

212 

213 Defined once because it is built at match time 

214 (_run_addresses_by_given, which is how post_rules' H1 and group's 

215 P5 licence both reach it) and wherever a caller's word is stored or 

216 looked up (_edit_words, which folds every word add() and remove() 

217 take, a phrase included, and readings_of), and a divergence between 

218 them fails silently: the entry simply stops matching.""" 

219 return " ".join(_fold_words(words)) 

220 

221 

222def _run_addresses_by_given(words: Iterable[str], 

223 vocabulary: Set[str]) -> bool: 

224 """Whether a run of title words addresses by the GIVEN name. 

225 

226 Two sites ask it and they must agree -- post_rules for H1, group 

227 for the P5 licence -- because a run read two ways is a rule 

228 contradicting itself (decisions/P5, the 2026-08-22 #369 entry). 

229 One predicate, so they cannot drift. 

230 

231 The WHOLE run's key, or that key's LAST word (#489): a run is 

232 written as several titles and addresses the way its final one does, 

233 so 'Her Majesty Queen' addresses by given name because 'queen' 

234 does. The two arms are asked of one key and neither is the other's 

235 fallback -- the `or` short-circuits but decides nothing, since for 

236 a one-word run the key IS its last word. Both arms read one 

237 _fold_words list, so the last word is the last word of the FOLDED 

238 key by construction rather than by agreement, and a run token that 

239 folds away cannot empty that arm: the conjunction merge can put a 

240 lone '.' in the run ('Sir and . John'), and the fold drops it. 

241 What the drop leaves as the last word can then be the CONJUNCTION 

242 -- 'Sir and . John' keys 'sir and' and reads family 'John', where 

243 'Sir and Dame John' keys 'sir and dame' and reads given. Harmless 

244 on the shipped vocabulary, which holds no entry ending in a 

245 connective, and a caller who stored one would be asking for it 

246 (measured 2026-09-09). 

247 

248 The whole-run arm is what keeps a caller's multi-word phrase entry 

249 working: 'lt col' is stored as one key and matched as one run. Over 

250 the SHIPPED vocabulary it is dead -- every shipped entry is a single 

251 word (asserted in test_lexicon.py), so it can only ever match a 

252 one-word run, which is a run the last-word arm reads the same way. 

253 

254 H2's unlisted abbreviations ride in the run. One can never match as 

255 the last-word key, being in no vocabulary by definition -- written 

256 as the inputs that produce those runs, 'Xyz. Sir John' keys 'xyz 

257 sir', matches on 'sir' and reads given 'John', while 'Sir Xyz. 

258 John' keys 'sir xyz', matches on neither arm and reads family 

259 'John'. It CAN sit inside a whole-run key that matches, because 

260 given_name_titles is deliberately not validated against titles: a 

261 caller who stores 'sir xyz' makes 'Sir Xyz. John' read given. 

262 

263 The vocabulary is passed in rather than read off a default: a 

264 caller's own Lexicon is the one that has to be consulted, and this 

265 module is where Lexicon is defined.""" 

266 folded = _fold_words(words) 

267 if not folded: 

268 # every word folded away, so there is no key and no last word: 

269 # the joined spelling built "" here, which matched nothing 

270 return False 

271 return " ".join(folded) in vocabulary or folded[-1] in vocabulary 

272 

273 

274def _reject_buffer(value: object, label: str, plural: str) -> None: 

275 """Binary sequences iterate to INTS, so every downstream entry check 

276 reports a byte value -- "must be strings, got 100" for b'dr', where 

277 100 is 'd'. That names neither the cause nor the fix. v1 shipped a 

278 decode hint for this (#238), and parse() carries one, so no config 

279 entry point should be the odd one out. 

280 """ 

281 if isinstance(value, (bytes, bytearray, memoryview)): 

282 raise TypeError( 

283 f"{label} must be an iterable of {plural}, not " 

284 f"{type(value).__name__} -- decode first, e.g. " 

285 f"raw.decode('utf-8')" 

286 ) 

287 

288 

289@functools.cache 

290def _pair_names(category: str) -> frozenset[str]: 

291 """Every name a shipped `category` reading (familiar or spelling) 

292 lists as its pair's other name, `short_for` or `spelling_of`, read 

293 from the reading index once: the names #1535's warning tells apart 

294 from a word in no file, whatever pairs a lexicon has compiled.""" 

295 ri = _index_module() 

296 prop = ri.MATCHING_LISTS[category] 

297 return frozenset( 

298 _normalize(name) for r in ri.index() if r.kind == category 

299 for name in r.props.get(prop) or ()) 

300 

301 

302def _warn_at_caller(message: str) -> None: 

303 # A fixed stacklevel always lands on library internals: the call 

304 # depth differs per entry point (Lexicon(), add(), unpickle, 

305 # dataclasses.replace). Walk out of this module (and dataclasses' 

306 # replace frames) so the warning points at the caller's own line. 

307 level = 2 

308 frame: FrameType | None = sys._getframe(1) 

309 while frame is not None and frame.f_globals.get("__name__") in ( 

310 __name__, "dataclasses"): 

311 frame, level = frame.f_back, level + 1 

312 warnings.warn(message, UserWarning, stacklevel=level) 

313 

314 

315def _normset(entries: Iterable[str], field_name: str) -> frozenset[str]: 

316 # Reject a bare str before iterating: iterating "dr" would silently 

317 # yield the single characters {'d', 'r'} -- the set(str) footgun on 

318 # the primary customization surface. 

319 if isinstance(entries, str): 

320 raise TypeError( 

321 f"Lexicon.{field_name} must be an iterable of strings, " 

322 f"not a bare string" 

323 ) 

324 _reject_buffer(entries, f"Lexicon.{field_name}", "strings") 

325 # A Mapping would silently contribute only its keys; a dict here 

326 # almost always means the caller confused this field with 

327 # capitalization_exceptions. 

328 if isinstance(entries, Mapping): 

329 raise TypeError( 

330 f"Lexicon.{field_name} must be an iterable of strings, not a " 

331 f"mapping (only capitalization_exceptions holds key->value pairs)" 

332 ) 

333 try: 

334 items = tuple(entries) # materialize once; entries may be a generator 

335 except TypeError: 

336 raise TypeError( 

337 f"Lexicon.{field_name} must be an iterable of strings, " 

338 f"got {entries!r}" 

339 ) from None 

340 normalized = set() 

341 for w in items: 

342 if not isinstance(w, str): 

343 raise TypeError( 

344 f"Lexicon.{field_name} entries must be strings, got {w!r}" 

345 ) 

346 n = _normalize(w) 

347 # "." or "" is a data bug (stray split artifact, empty CSV 

348 # cell); dropping it silently would also let a data-module typo 

349 # vanish instead of failing CI. 

350 if not n: 

351 raise ValueError( 

352 f"Lexicon.{field_name} entry {w!r} normalizes to empty " 

353 f"(lowercase + strip full stops/whitespace leaves nothing)" 

354 ) 

355 # A list is matched one word at a time, so a multi-word entry 

356 # can never match -- the library itself shipped eight such dead 

357 # entries for years (repaired 2026-07-26). Warn, never raise: an 

358 # inert entry produces nothing, while a raise costs a working 

359 # configuration (AGENTS.md's gotcha on given-name title runs, 

360 # the precedent). split() covers all Unicode whitespace. 

361 if n != "".join(n.split()): 

362 _warn_at_caller( 

363 f"Lexicon.{field_name} entries are matched one word at " 

364 f"a time; multi-word entry {w!r} can never match. " 

365 f"Split it into separate entries") 

366 normalized.add(n) 

367 return frozenset(normalized) 

368 

369 

370def _alnum(text: str) -> str: 

371 return "".join(c for c in text if c.isalnum()) 

372 

373 

374def _offered_mask(normalized_key: str) -> str: 

375 """The working value a mismatched-mask error offers: the 

376 key upper-cased, or the key unchanged -- an identity mask, always 

377 legal -- where .upper() changes the letter count ('straße' -> 

378 'STRASSE') and would fail the check if pasted back in.""" 

379 upper = normalized_key.upper() 

380 return upper if _alnum(_normalize(upper)) == _alnum( 

381 normalized_key) else normalized_key 

382 

383 

384class _MaskValueError(ValueError): 

385 """_normpairs' error for a value that does not spell its key. 

386 Built in the UnicodeDecodeError idiom -- structure in, message 

387 out: `key`, `normalized_key` and `value` are the offending inputs; 

388 `offered` (the fix quoted in the message below) is computed from 

389 them, not carried separately. 

390 

391 __reduce__ is explicit because the inherited one re-calls 

392 __init__ with self.args, which holds the message alone, not the 

393 three fields __init__ needs -- and a ProcessPoolExecutor pickles a 

394 worker's exception to deliver it, surfacing a construction failure 

395 as BrokenProcessPool. Passing self.__dict__ as reduce's third 

396 element (restored via a plain __dict__.update, there being no 

397 __setstate__ here) carries along anything added after construction 

398 -- e.g. add_note() -- that reconstructing from the three fields 

399 alone would not. (An exception, so _types.py's frozen-dataclass 

400 pickle guards do not apply.)""" 

401 

402 def __init__(self, key: str, normalized_key: str, value: str) -> None: 

403 self.key = key 

404 self.normalized_key = normalized_key 

405 self.value = value 

406 self.offered = _offered_mask(normalized_key) 

407 super().__init__( 

408 f"capitalization_exceptions value {value!r} for key {key!r} " 

409 f"does not spell the key's letters and digits: a value " 

410 f"is a case mask, the key's own letters and digits " 

411 f"recased -- e.g. dataclasses.replace(lexicon, " 

412 f"capitalization_exceptions=(*lexicon." 

413 f"capitalization_exceptions, ({normalized_key!r}, " 

414 f"{self.offered!r})))") 

415 

416 def __reduce__( 

417 self, 

418 ) -> tuple[type[_MaskValueError], tuple[str, str, str], dict[str, object]]: 

419 return (type(self), (self.key, self.normalized_key, self.value), 

420 self.__dict__) 

421 

422 

423def _normpairs( 

424 raw: Mapping[str, str] | Iterable[tuple[str, str]], 

425) -> tuple[tuple[str, str], ...]: 

426 """Canonicalize capitalization_exceptions input: _normset's sibling 

427 for the one pair-valued field. Dedupes on the NORMALIZED key so the 

428 tuple and the derived map always agree ("PHD" and "phd" collide 

429 after normalization; "Ph.D." does not, the fold keeping interior 

430 periods, so it is a key of its own, "ph.d"); last occurrence wins, 

431 matching dict semantics and the right-bias rule used elsewhere.""" 

432 if isinstance(raw, str): 

433 raise TypeError( 

434 "capitalization_exceptions must be a mapping or an " 

435 "iterable of (key, value) pairs, not a bare string" 

436 ) 

437 _reject_buffer(raw, "capitalization_exceptions", "(key, value) pairs") 

438 pairs = raw.items() if isinstance(raw, Mapping) else raw 

439 try: 

440 pairs = iter(pairs) 

441 except TypeError: 

442 raise TypeError( 

443 "capitalization_exceptions must be a mapping or an " 

444 f"iterable of (key, value) pairs, got {raw!r}" 

445 ) from None 

446 deduped: dict[str, str] = {} 

447 for entry in pairs: 

448 # A 2-char str entry would unpack "ab" into ("a", "b") 

449 # silently, so reject str outright; other mis-shapes would 

450 # otherwise surface as bare unpack errors. 

451 if isinstance(entry, str): 

452 raise TypeError( 

453 f"capitalization_exceptions entries must be " 

454 f"(key, value) pairs, got {entry!r}" 

455 ) 

456 try: 

457 k, v = entry 

458 except (TypeError, ValueError): 

459 raise TypeError( 

460 f"capitalization_exceptions entries must be " 

461 f"(key, value) pairs, got {entry!r}" 

462 ) from None 

463 if not isinstance(k, str) or not isinstance(v, str): 

464 raise TypeError( 

465 f"capitalization_exceptions entries must be " 

466 f"str -> str, got {k!r}: {v!r}" 

467 ) 

468 normalized_key = _normalize(k) 

469 if not normalized_key: 

470 raise ValueError( 

471 f"capitalization_exceptions key {k!r} normalizes to " 

472 f"empty (lowercase + strip full stops/whitespace leaves " 

473 f"nothing)" 

474 ) 

475 # Stored NFC-composed, case kept (unicodedata, not _normalize): 

476 # one stored spelling per value, whichever form the caller 

477 # wrote. _apply_mask reads both forms alike since #542 

478 # (_render._beside looks past combining marks); before it, a 

479 # decomposed letter read as a base letter split off beside a 

480 # non-alpha combining mark. The mask check below 

481 # passes either spelling, _normalize composing both of its 

482 # sides. `written` keeps the caller's own spelling -- composed 

483 # or not -- for the mismatch error below: a decomposed value 

484 # (e.g. 'e' + a combining acute) and its NFC form print 

485 # identically to a reader's eye but are different str objects, 

486 # so echoing the composed spelling back would show the caller 

487 # a value they did not write. 

488 written = v 

489 v = unicodedata.normalize("NFC", v) 

490 # capitalized() looks words up one at a time (the _WORD regex 

491 # never yields spaces), so a multi-word key is unreachable -- 

492 # checked FIRST, ahead of the mask check below, because an 

493 # invariant guards harm and a value that can never be read 

494 # does no harm no matter what it says (AGENTS.md: "a check 

495 # guards harm, not no-ops"). Raising the mask error for such a 

496 # key -- as a naive mask-first order does -- would refuse a 

497 # config that was always going to be a no-op. 

498 # interior whitespace test; split() covers all Unicode whitespace 

499 if normalized_key != "".join(normalized_key.split()): 

500 _warn_at_caller( 

501 f"capitalization_exceptions keys are matched one word " 

502 f"at a time; multi-word key {k!r} can never match. " 

503 f"Split it into per-word entries") 

504 deduped[normalized_key] = v 

505 continue 

506 # A value is a case MASK (#459): the key's own letters and 

507 # digits recased, compared through the key's own fold. Its 

508 # punctuation marks which letters are joined into one run 

509 # (_render._apply_mask reads that) and is never written into 

510 # the word. A raise, not a warning: a mismatched value used to 

511 # be SUBSTITUTED for the word, and rules/R4: "Repair 

512 # changes case and nothing else", so there is no reading of 

513 # one that repair can honor. 

514 if _alnum(_normalize(v)) != _alnum(normalized_key): 

515 # key is the RAW key, not normalized_key, and `written`, 

516 # not `v`: the message names the entry as the caller wrote 

517 # it, not as the fold or NFC composed it. 

518 raise _MaskValueError(k, normalized_key, written) 

519 deduped[normalized_key] = v 

520 return tuple(sorted(deduped.items())) 

521 

522 

523#: The two lists outside the per-word model (decisions/vocabulary-model's 

524#: Standing line on name readings): `Lexicon` fields, changed through 

525#: ``|`` with a fragment or ``dataclasses.replace``, and copied into 

526#: `_LexiconSets` beside the compiled sets. 

527_LIST_FIELDS = ("surnames", "given_names") 

528 

529#: The 20 sets a compile of readings gives, under the names the 2.x 

530#: `Lexicon` fields had: internal since 3.0 (#754, 4i-b), read through 

531#: `Lexicon._sets`, and the names an old spelling is refused by. 

532_SET_FIELDS = tuple(f for f in _VOCAB_FIELDS if f not in _LIST_FIELDS) 

533 

534#: The 2.x spellings a call is refused by (`_refusal`): every 2.x 

535#: `Lexicon` field, the masks among them. 

536_2X_FIELDS = frozenset(_VOCAB_FIELDS) | {"capitalization_exceptions"} 

537 

538 

539@dataclass(frozen=True, slots=True, eq=False, repr=False) 

540class _LexiconSets: 

541 """The vocabulary sets a parse reads: the pipeline, `_render`, 

542 `_parser` and the tools read `lexicon._sets.titles` (#754, 4i-a; 

543 tests/v2/test_layering.py holds it), the 2.x public fields having 

544 become internal in 4i-b. One attribute per `_VOCAB_FIELDS` entry, in 

545 that order, then one per `_KIND_FIELDS` entry, each a frozenset, so 

546 a membership test stays a C-level attribute read and costs no frame. 

547 

548 Built once per `Lexicon`, at construction: the compiled sets from 

549 its readings by `compile_readings`, or for `Lexicon.default()` from 

550 nameparser/config/_compiled.py, so the reading index stays unloaded 

551 on `parse("John Smith")`; the two lists from its fields. Never 

552 compared, hashed or pickled: a `Lexicon`'s equality and pickle are 

553 its fields', and a load or a `dataclasses.replace` builds this 

554 again. 

555 

556 Not a mapping and no repr of its own: it holds whole word lists, 

557 and a repr of them would be unbounded.""" 

558 

559 titles: frozenset[str] 

560 given_name_titles: frozenset[str] 

561 suffix_acronyms: frozenset[str] 

562 suffix_words: frozenset[str] 

563 suffix_acronyms_ambiguous: frozenset[str] 

564 particles: frozenset[str] 

565 particles_ambiguous: frozenset[str] 

566 conjunctions: frozenset[str] 

567 conjunctions_ambiguous: frozenset[str] 

568 bound_given_names: frozenset[str] 

569 given_name_abbreviations: frozenset[str] 

570 maiden_markers: frozenset[str] 

571 surnames: frozenset[str] 

572 honorific_tails: frozenset[str] 

573 after_given_titles: frozenset[str] 

574 suffix_words_ambiguous: frozenset[str] 

575 agnomens: frozenset[str] 

576 titles_ambiguous: frozenset[str] 

577 title_modifiers: frozenset[str] 

578 title_styles: frozenset[str] 

579 title_phrases: frozenset[str] 

580 given_names: frozenset[str] 

581 #: the suffix words whose suffix reading is a generation (`jr`, 

582 #: `iii`), a credential written as a word (`kc`), or an honorific 

583 #: (`さん`, `先生`), and the particles read as patronymics (`bin`): 

584 #: the kinds rules/R8's and rules/R9's views read, which the sets 

585 #: above do not record 

586 generation_words: frozenset[str] 

587 credential_words: frozenset[str] 

588 honorific_words: frozenset[str] 

589 patronymic_particles: frozenset[str] 

590 #: the words whose title reading is written `abbreviation=True` 

591 #: (`maj`); rules/H5's trailing chain reads one only beside 

592 #: `titles_ambiguous`, through classify's TRAILING_TITLE_TAG (#999) 

593 title_abbreviations: frozenset[str] 

594 #: the suffix words written `title_case_is_name=True` (`fils`, 

595 #: `kc`), whose writing leans where a name reading gates them: 

596 #: lower case is the suffix, Title case the name (rules/S6, #1039) 

597 title_case_name_words: frozenset[str] 

598 #: the names written `shared=True` (Sikh `kaur`, `singh`), which a 

599 #: community gives every member: rules/O6 and O7 neither take nor 

600 #: complete one, and P10 completes none (#704) 

601 shared_names: frozenset[str] 

602 #: the given names written `after_particle=True` (`carmen`), the 

603 #: second of a compound given name written behind a particle 

604 #: (`María del Carmen`): rules/P10 reads one as a middle name behind 

605 #: a one-word given name, and O6 leaves it there (#704) 

606 particle_given_names: frozenset[str] 

607 #: the particles of the `saint` kind (`san`, `santa`, `st`, `ste`): no given 

608 #: name phrase opens with one, `Santa María` being a surname (#704) 

609 saint_particles: frozenset[str] 

610 #: the particles of the kinds written with a capital, `saint` and 

611 #: `rank` (`st`, `san`, `freiherr`, `graf`): rules/R4's case repair 

612 #: writes one as a name word, not in lowercase (#1069) 

613 capitalized_particles: frozenset[str] 

614 #: the particles written `capital_opening=True` (`ter`, `der`): 

615 #: rules/R12's case repair writes one with a capital where no 

616 #: particle stands before it in the family name, nor, where it opens 

617 #: the family name, written right before it in any role (`Levon Ter 

618 #: Petrosyan`, but `Van der Walt`) 

619 capital_opening_particles: frozenset[str] 

620 #: the titles written `dotted=True` (`us`, `uk`, `pd`): rules/H10 

621 #: reads a run of single letters joined by full stops that spells 

622 #: one, at the head of a name (the given part's title run, or H6's 

623 #: before a family comma), as that title where a title the run keeps 

624 #: stands behind it (`U.S. District Judge`, #490) 

625 dotted_titles: frozenset[str] 

626 #: the titles written `attached="before"` (Thai `นาย`, `นางสาว`, 

627 #: `อาจารย์`): rules/W6 splits one off the start of the name's first 

628 #: word it is glued to, the mirror of `honorific_tails` (#317) 

629 glued_titles: frozenset[str] 

630 #: the two-word given names a bound word's `completed_by` lists 

631 #: ('عبد الله'), which rules/P12 joins past the first name word (#694) 

632 bound_phrases: frozenset[str] 

633 #: the bound given names that complete with any plain name word 

634 #: after them past the first name word, and the ones of those that 

635 #: do so only in a name of four words or more (rules/P12, #1464) 

636 bound_completes_any: frozenset[str] 

637 bound_long_names_only: frozenset[str] 

638 #: the words a bound pair writes second and joins from, and the 

639 #: pairs a reading written `completes` lists ('ذو الغنى'); a word 

640 #: with a reading listing none joins behind any plain word, at the 

641 #: first name word too (rules/P12, #1072) 

642 bound_seconds: frozenset[str] 

643 bound_second_phrases: frozenset[str] 

644 #: the words of `bound_seconds` every reading of which lists 

645 #: `completes`, joining behind those words alone 

646 bound_seconds_listed: frozenset[str] 

647 #: the words that announce a second name the person is known by 

648 #: (`@`, `urf`), which rules/N4 reads the words after as the 

649 #: nickname (#1164) 

650 alias_markers: frozenset[str] 

651 

652 

653#: Lexicon field -> the compiled constant it is read from, for every 

654#: set the vocabulary compiles (nameparser/_reading_index.py's 

655#: Compiled); `particles_ambiguous` is derived (_vocab_fields below). 

656#: tests/v2/test_parser.py holds that these, read from the compile of 

657#: no choice, are Lexicon.default()'s. 

658_COMPILED_FIELDS = { 

659 "titles": "TITLES", 

660 "given_name_titles": "GIVEN_NAME_TITLES", 

661 "suffix_acronyms": "SUFFIX_ACRONYMS", 

662 "suffix_words": "SUFFIX_WORDS", 

663 "suffix_acronyms_ambiguous": "SUFFIX_ACRONYMS_AMBIGUOUS", 

664 "particles": "PARTICLES", 

665 "conjunctions": "CONJUNCTIONS", 

666 "conjunctions_ambiguous": "CONJUNCTIONS_AMBIGUOUS", 

667 "bound_given_names": "BOUND_GIVEN_NAMES", 

668 "given_name_abbreviations": "GIVEN_NAME_ABBREVIATIONS", 

669 "maiden_markers": "MAIDEN_MARKERS", 

670 "honorific_tails": "GLUED_HONORIFICS", 

671 "after_given_titles": "AFTER_GIVEN_TITLES", 

672 "suffix_words_ambiguous": "SUFFIX_WORDS_AMBIGUOUS", 

673 "agnomens": "AGNOMENS", 

674 "titles_ambiguous": "TITLES_AMBIGUOUS", 

675 "title_modifiers": "TITLE_MODIFIERS", 

676 "title_styles": "TITLE_STYLES", 

677 "title_phrases": "TITLE_PHRASES", 

678 "generation_words": "GENERATION_WORDS", 

679 "credential_words": "CREDENTIAL_WORDS", 

680 "honorific_words": "HONORIFIC_WORDS", 

681 "patronymic_particles": "PATRONYMIC_PARTICLES", 

682 "title_abbreviations": "TITLE_ABBREVIATIONS", 

683 "title_case_name_words": "TITLE_CASE_NAME_WORDS", 

684 "shared_names": "SHARED_NAMES", 

685 "particle_given_names": "PARTICLE_GIVEN_NAMES", 

686 "saint_particles": "SAINT_PARTICLES", 

687 "capitalized_particles": "CAPITALIZED_PARTICLES", 

688 "capital_opening_particles": "CAPITAL_OPENING_PARTICLES", 

689 "dotted_titles": "DOTTED_TITLES", 

690 "glued_titles": "GLUED_TITLES", 

691 "bound_phrases": "BOUND_PHRASES", 

692 "bound_completes_any": "BOUND_COMPLETES_ANY", 

693 "bound_long_names_only": "BOUND_LONG_NAMES_ONLY", 

694 "bound_seconds": "BOUND_SECONDS", 

695 "bound_second_phrases": "BOUND_SECOND_PHRASES", 

696 "bound_seconds_listed": "BOUND_SECONDS_LISTED", 

697 "alias_markers": "ALIAS_MARKERS", 

698} 

699 

700#: What the 2.x sets do not record: the kinds the views read (rules/R8, 

701#: rules/R9), and the titles written short that rules/H5's trailing 

702#: chain and rules/H9's article partner read where one may also be a 

703#: given name (#999), which is no kind; the name is the tuple's first 

704#: use. `_LexiconSets` attributes after the `_VOCAB_FIELDS` ones, each 

705#: a compiled constant of its own: the tail of `_COMPILED_FIELDS`. 

706_KIND_FIELDS = tuple(f for f in _COMPILED_FIELDS if f not in _VOCAB_FIELDS) 

707 

708 

709#: The groups `SAME_AS` is keyed by, one per kind of role a name match 

710#: compares (`_reading_index.SAME_AS_GROUPS` maps a reading's kind to 

711#: one; tests/v2/test_lexicon.py holds the two to one list). 

712_SAME_AS_GROUPS = frozenset({"given", "family", "title", "suffix"}) 

713 

714#: A group -> word -> the words it is a listed spelling of. 

715SameAs = Mapping[str, Mapping[str, frozenset[str]]] 

716 

717 

718def _same_as_of(compiled: Mapping[str, Any]) -> SameAs: 

719 """The compile's `SAME_AS` as the lexicon keeps it: per group, each 

720 word's full forms normalized, as a caller's `same_as` is written 

721 free-form.""" 

722 return MappingProxyType({ 

723 group: MappingProxyType({ 

724 w: frozenset(_normalize(h) for h in heads) 

725 for w, heads in words.items()}) 

726 for group, words in compiled["SAME_AS"].items()}) 

727 

728 

729def _vocab_fields(compiled: Mapping[str, Any]) -> dict[str, frozenset[str]]: 

730 """The sets a compile of the vocabulary gives, by `_LexiconSets` 

731 name (the constants of nameparser/config/_compiled.py, or a compile 

732 of readings), the two lists aside.""" 

733 out = {name: compiled[key] for name, key in _COMPILED_FIELDS.items()} 

734 # FLIPPED from v1: v1 marked the never-given subset; the sets mark 

735 # the may-be-given one 

736 out["particles_ambiguous"] = (compiled["PARTICLES"] 

737 - compiled["NON_GIVEN_NAME_PARTICLES"]) 

738 return out 

739 

740 

741#: A group -> the words of it with a listed spelling that are a name of 

742#: their own too (`SAME_AS_NAMED`). 

743SameAsNamed = Mapping[str, frozenset[str]] 

744 

745 

746# -- the name match's fold, which the familiar-form index shares -------- 

747 

748#: Full stops and apostrophes: the typed one, the typographic U+2019, 

749#: the modifier letter U+02BC, and Uzbek Latin's other spellings of 

750#: the `ʻ` in `oʻ` and `gʻ` (U+02BB, U+2018, the backtick), so 

751#: `O’Brien` folds to `obrien` and `Gʻofurov` to `gofurov` 

752#: (decisions/name-matching, 2026-11-09). And the Arabic tatweel U+0640, 

753#: which `_normalize` deletes too (#1151), so a name's two spellings that 

754#: differ by one fold alike where the vocabulary and the match meet. 

755_DROPPED = str.maketrans("", "", ".'`\u2019\u02bc\u02bb\u2018\u0640") 

756#: The hyphens the parser joins two names with (rules/O6), defined here, 

757#: below the pipeline, so the match's forms and the lexicon's pair index 

758#: (`_forms`) read them alike; `_pipeline._vocab` reads them from here. 

759_HYPHEN_CHARS = "-\u2010\u2011\u2012\u2013\u2212\ufe63\uff0d" 

760#: A ZWNJ or ZWJ beside whitespace, a hyphen or the text's edge, as 

761#: `_normalize` strips one at a token's edge (#1335). The hyphen counts 

762#: because the match cuts a family name at its hyphens and folds each 

763#: half (`_match._family_words`), so `Smith-Jones` with a ZWNJ before 

764#: its hyphen folds alike whole and by halves; one between letters is 

765#: kept. 

766_NOT_AN_EDGE = r"[^\s" + "".join(f"\\u{ord(c):04x}" for c in _HYPHEN_CHARS) + "]" 

767_EDGE_JOINER = re.compile( 

768 rf"(?<!{_NOT_AN_EDGE})[\u200c\u200d]+|[\u200c\u200d]+(?!{_NOT_AN_EDGE})") 

769_TO_HYPHEN_MINUS = str.maketrans(dict.fromkeys(_HYPHEN_CHARS, "-")) 

770#: The scripts whose combining marks `_fold` drops as accents. 

771_ACCENTED_SCRIPTS = ("LATIN ", "GREEK ", "CYRILLIC ") 

772#: The Latin letters NFD leaves whole that a keyboard lacks, written as 

773#: one types them: `ł` as `l`, `ı` as `i`, `ø` as `o`, `đ` and `ð` as 

774#: `d`, `þ` as `th`, `æ` as `ae`, `œ` as `oe` (`ß` is `ss` through 

775#: casefolding already), so `Łukasz` / `Lukasz` and `Pınar` / `Pinar` 

776#: read `folded`: a spelling no one chooses (decisions/name-matching, 

777#: 2026-11-12 A KEYBOARD'S SPELLING IS FOLDED). `_suggest.fold`'s table 

778#: less its pinyin `ü` as `v`, and with Icelandic `ð` and `þ`; lower case 

779#: only, as the fold casefolds first. 

780_KEYBOARD = str.maketrans({"ł": "l", "ı": "i", "ø": "o", "đ": "d", 

781 "ð": "d", "þ": "th", "æ": "ae", "œ": "oe"}) 

782 

783def _fold(text: str) -> str: 

784 """The text with case, accents, full stops and apostrophes folded 

785 away: NFC, `.` and the apostrophes and their stand-ins (`_DROPPED`) removed, 

786 NFD, casefolded, then NFC again, so the folded text, and every key 

787 cut from it, is precomposed (a Hangul syllable, never a conjoining 

788 jamo). Hyphens and spaces are kept. A combining mark (Mn) is dropped 

789 only where the letter it attaches to is Latin, Greek or Cyrillic, 

790 where it is an accent; in another script (a Devanagari virama, 

791 anusvara or vowel sign) it is spelling and is kept. A letter counts 

792 as in those scripts where it or its casefolded form is, so a letter 

793 that casefolds into one (the micro sign U+00B5 into Greek mu, U+2183 

794 into Latin) loses its mark on the first fold, which keeps the fold 

795 idempotent; so does removing the full stops and apostrophes before 

796 the marks are read, a mark after one then attaching to the letter 

797 before it, and again after casefolding, which can write one (U+0149 

798 `ʼn` casefolds to `ʼn`). The iota subscript U+0345 is a mark like any 

799 other, so `ᾳ` folds to `α`. A ZWNJ or ZWJ beside whitespace, a 

800 hyphen or the text's edge is dropped with the full stops 

801 (`_EDGE_JOINER`), as `_normalize` drops one at a token's edge. Last, the letters a keyboard lacks are written as one types them 

802 (`_KEYBOARD`).""" 

803 if text.isascii(): 

804 # no accent, no composition, and no apostrophe but the typed 

805 # one and the backtick 

806 return text.casefold().translate(_DROPPED) 

807 dropped = unicodedata.normalize("NFC", text).translate(_DROPPED) 

808 if "\u200c" in dropped or "\u200d" in dropped: 

809 dropped = _EDGE_JOINER.sub("", dropped) 

810 decomposed = unicodedata.normalize("NFD", dropped) 

811 kept = [] 

812 accented = False 

813 for c in decomposed: 

814 if unicodedata.category(c) == "Mn": 

815 if accented: 

816 continue 

817 else: 

818 accented = (unicodedata.name(c, "").startswith(_ACCENTED_SCRIPTS) 

819 or unicodedata.name(c.casefold()[:1] or c, "") 

820 .startswith(_ACCENTED_SCRIPTS)) 

821 kept.append(c) 

822 # again after casefolding, which can write an apostrophe (U+0149) 

823 return unicodedata.normalize( 

824 "NFC", "".join(kept).casefold().translate(_DROPPED)).translate( 

825 _KEYBOARD) 

826 

827 

828#: The letters a standard transcription writes out where a keyboard or 

829#: an encoding lacks them: German `ä` `ö` `ü` as `ae` `oe` `ue`, Danish 

830#: and Norwegian `ø` and `å` as `oe` and `aa`, Serbo-Croatian `đ` as 

831#: `dj`. A word holding one also reads as its transcription, a second 

832#: folded form (`_forms`), so `Müller` / `Mueller` and `Srđan` / 

833#: `Srdjan` read `folded` (decisions/name-matching, 2026-11-12 A 

834#: KEYBOARD'S SPELLING IS FOLDED); lower case only, as it is applied 

835#: to the casefolded word. 

836_TRANSCRIBED: Mapping[str, str] = {"ä": "ae", "ö": "oe", "ü": "ue", 

837 "ø": "oe", "å": "aa", "đ": "dj"} 

838#: The most letters of `_TRANSCRIBED` a text is read letter by letter 

839#: for (2 ** this many forms); past it, all of them transcribed or none. 

840_MOST_TRANSCRIBED = 8 

841 

842 

843@functools.lru_cache(maxsize=4096) 

844def _forms(text: str) -> frozenset[str]: 

845 """The text's folded forms: each letter of `_TRANSCRIBED` it holds 

846 (its decomposed spelling included) written as the keyboard writes it 

847 or as its transcription, letter by letter, so a text mixing the two 

848 (`Ødegård` / `Odegaard`, `Müller Lüdenscheidt` / `Mueller 

849 Ludenscheidt`) meets it too. Two texts read `folded` where any forms 

850 meet. A written-out word (`Mueller`) has one form, which meets one of 

851 the word written with the letter (`Müller`), so the reading is 

852 symmetric; and `Muller` and `Mueller` each meet `Müller` and not each 

853 other.""" 

854 lowered = unicodedata.normalize("NFC", text.casefold()).translate( 

855 _TO_HYPHEN_MINUS) 

856 slots = [i for i, c in enumerate(lowered) if c in _TRANSCRIBED] 

857 if not slots: 

858 return frozenset((_fold(lowered),)) 

859 if len(slots) > _MOST_TRANSCRIBED: 

860 written = "".join(_TRANSCRIBED.get(c, c) for c in lowered) 

861 return frozenset((_fold(lowered), _fold(written))) 

862 out = set() 

863 for choice in itertools.product((False, True), repeat=len(slots)): 

864 chars = list(lowered) 

865 for i, transcribe in zip(slots, choice): 

866 if transcribe: 

867 chars[i] = _TRANSCRIBED[chars[i]] 

868 out.add(_fold("".join(chars))) 

869 return frozenset(out) 

870 

871 

872#: A given name -> every name it is paired with as a familiar form, in 

873#: either direction (`FAMILIAR`, read both ways). 

874Familiar = Mapping[str, frozenset[str]] 

875 

876 

877def _familiar_of(pairs: Mapping[str, Iterable[str]]) -> Familiar: 

878 """The compile's `FAMILIAR`, a familiar form -> the longer names its 

879 `short_for` lists, read both ways: each word with every name it is 

880 paired with directly, as the shorter name or the longer. A caller 

881 does not always write the shorter name first (`barbara` / `babs`), 

882 so the match reads a pair whichever way it was written, and never chains 

883 two pairs (decisions/name-matching, 2026-11-08 

884 FAMILIAR FORMS). Each name is indexed under its fold too (`_fold`, 

885 the match's own), and under every transcription of it (`_forms`), 

886 so a pair written accented (`józsi`, `józsef`) is found from either 

887 name written without its accents or written out (`günni`, `guenni`). 

888 Given `ALTERNATE_SPELLINGS`, the same index of the alternate 

889 spellings, which pair alike (decisions/name-matching, 2026-11-12 

890 ALTERNATE SPELLINGS ARE OPT-IN).""" 

891 paired: dict[str, set[str]] = {} 

892 for short, longs in pairs.items(): 

893 for long in longs: 

894 for key in {short} | _forms(short): 

895 paired.setdefault(key, set()).add(long) 

896 for key in {long} | _forms(long): 

897 paired.setdefault(key, set()).add(short) 

898 return MappingProxyType({w: frozenset(ns) for w, ns in paired.items()}) 

899 

900 

901#: What a lexicon's readings compile to: the vocabulary sets by 

902#: `_LexiconSets` name, the listed-spelling map, the words in it that 

903#: are a name of their own as well, the familiar forms and the alternate 

904#: spellings. 

905_Compiled = tuple[Mapping[str, frozenset[str]], SameAs, SameAsNamed, 

906 Familiar, Familiar] 

907 

908 

909def _compiled_of(compiled: Mapping[str, Any]) -> _Compiled: 

910 return (MappingProxyType(_vocab_fields(compiled)), _same_as_of(compiled), 

911 MappingProxyType(dict(compiled["SAME_AS_NAMED"])), 

912 _familiar_of(compiled["FAMILIAR"]), 

913 _familiar_of(compiled["ALTERNATE_SPELLINGS"])) 

914 

915 

916@functools.cache 

917def _default_compiled() -> _Compiled: 

918 # the compiled data module is the default's one source, so the 

919 # default never loads the reading index (decisions/vocabulary- 

920 # model, 2026-10-29 3a; its 2026-11-02 #754 entry, item 4) 

921 import nameparser.config._compiled as compiled 

922 return _compiled_of(vars(compiled)) 

923 

924 

925_NO_SETS: Mapping[str, frozenset[str]] = MappingProxyType( 

926 {name: frozenset() for name in _COMPILED_FIELDS} | { 

927 "particles_ambiguous": frozenset()}) 

928#: What the empty base compiles to: no sets and no listed spellings. 

929_NOTHING_COMPILED: _Compiled = (_NO_SETS, MappingProxyType( 

930 {g: MappingProxyType({}) for g in sorted(_SAME_AS_GROUPS)}), 

931 MappingProxyType({g: frozenset() for g in sorted(_SAME_AS_GROUPS)}), 

932 MappingProxyType({}), MappingProxyType({})) 

933 

934 

935# -- readings ------------------------------------------------------------ 

936 

937#: A reading's properties as the log and the repr compare them: sorted 

938#: (key, value) pairs, a list value a sorted tuple. 

939_Props = tuple[tuple[str, Any], ...] 

940 

941#: The properties a caller never states on a reading: `default` (a 

942#: caller's reading is on) and `cased` (a case mask, configured through 

943#: `capitalization_exceptions`). 

944_UNSTATED = frozenset({"default", "cased"}) 

945 

946#: The properties that are true or false. 

947_FLAG_PROPS = frozenset({ 

948 "abbreviation", "acronym", "after_given", "may_be_initial", 

949 "title_case_is_name", "shared", "after_particle", "capital_opening", 

950 "dotted", "completes_any", "long_names_only"}) 

951 

952 

953class _Edit(NamedTuple): 

954 """One `add` or `remove`, stored frozen as written (decisions/ 

955 vocabulary-model, 2026-11-02 #754, item 3): its words normalized, 

956 its kind (None on a `remove` of every reading), its properties 

957 sorted pairs, a property given its unwritten value held as None, 

958 which removes it. A `remove` holds no properties, save the one pair 

959 list a `familiar` or `spelling` remove may name (`short_for`, 

960 `spelling_of`): the pairs to drop, where none drops every pair 

961 naming the word (decisions/name-matching, 2026-11-15 #1404). 

962 Compared and hashed as a tuple.""" 

963 

964 op: str 

965 words: tuple[str, ...] 

966 kind: str | None 

967 props: _Props 

968 

969 

970def _index_module() -> ModuleType: 

971 # the reading index's reader, imported at call time: tools/vocab/ 

972 # build.py loads this module by path, before the index it rewrites 

973 # can be trusted to import (root AGENTS.md's layering bullet) 

974 import nameparser._reading_index as ri 

975 return ri 

976 

977 

978def _clean(props: Mapping[str, Any]) -> _Props: 

979 """A reading's properties as a caller states them, `_UNSTATED` 

980 left out.""" 

981 return tuple(sorted((k, v) for k, v in props.items() 

982 if k not in _UNSTATED)) 

983 

984 

985def _unwritten(kind: str, prop: str) -> object: 

986 """The value `prop` takes on a `kind` reading that does not write 

987 it, read through _reading_index.ReadingProperties: `acronym` is 

988 true on a credential, `addresses` the family name.""" 

989 bare = _index_module().IndexReading("", "", kind, MappingProxyType({})) 

990 if prop == "acronym": 

991 return bare.acronym 

992 if prop == "addresses": 

993 return bare.addresses 

994 return bare.flag(prop) 

995 

996 

997#: The properties whose value is a list of words, each with what its 

998#: entries are and an example, for the messages refusing a value. 

999_LIST_PROPS: Mapping[str, str] = MappingProxyType({ 

1000 "attaches": "title kinds or title words, e.g. attaches=['military']", 

1001 "completed_by": "single words, e.g. completed_by=['الله']", 

1002 "completes": "single words, e.g. completes=['ذو']", 

1003 "short_for": "given names, e.g. short_for=['maxwell']", 

1004 "spelling_of": "given names, e.g. spelling_of=['olga']", 

1005}) 

1006 

1007#: Each matching-only category's list property: the names a familiar 

1008#: form stands for, the names a spelling is another spelling of. A 

1009#: caller's add of one EXTENDS the word's names in a reading of its own 

1010#: (decisions/name-matching, 2026-11-08 FAMILIAR FORMS and 2026-11-12 

1011#: ALTERNATE SPELLINGS ARE OPT-IN). 

1012#: `_reading_index.MATCHING_LISTS`, written here because this module 

1013#: reads that one only at call time (tests/v2/test_layering.py). 

1014_MATCHING_LISTS: Mapping[str, str] = MappingProxyType({ 

1015 "familiar": "short_for", "spelling": "spelling_of"}) 

1016#: Each matching-only category's example add, offered by the messages 

1017#: refusing one: code that runs (tests/v2/test_match.py executes it). 

1018_MATCHING_EXAMPLES: Mapping[str, str] = MappingProxyType({ 

1019 "familiar": "add('max', kind='familiar', short_for=['maxwell'])", 

1020 "spelling": "add('olha', kind='spelling', spelling_of=['olga'])"}) 

1021#: Each matching-only category's example remove of one pair, offered by 

1022#: the messages refusing one: code that runs, as the adds above do. 

1023_MATCHING_REMOVALS: Mapping[str, str] = MappingProxyType({ 

1024 "familiar": "remove('max', kind='familiar', short_for=['maxwell'])", 

1025 "spelling": "remove('olha', kind='spelling', spelling_of=['olga'])"}) 

1026 

1027 

1028def _prop_value(kind: str, prop: str, value: object) -> object: 

1029 """`value` canonical for the log, None where it is the unwritten 

1030 one (which removes the property).""" 

1031 if value is None or (isinstance(value, (bool, str)) 

1032 and value == _unwritten(kind, prop)): 

1033 return None 

1034 if prop in _FLAG_PROPS: 

1035 if not isinstance(value, bool): 

1036 raise TypeError(f"{prop} must be True or False, got {value!r}") 

1037 return value 

1038 if prop == "addresses": 

1039 if value != "given": 

1040 raise ValueError(f"addresses must be 'given' or 'family', " 

1041 f"got {value!r}") 

1042 return value 

1043 if prop == "attached": 

1044 # a suffix glued after the name (rules/W2) or a title glued in 

1045 # front of it (rules/W6), the side its category reads 

1046 side = ("before" if _index_module().CATEGORY.get(kind) == "title" 

1047 else "after") 

1048 if value != side: 

1049 raise ValueError(f"attached on {_a(kind)} {kind!r} reading must be " 

1050 f"{side!r} (a {'title peeled off the start' if side == 'before' else 'tail peeled off the end'} " 

1051 f"of a name token) or None, got {value!r}") 

1052 return value 

1053 if prop in _LIST_PROPS: 

1054 what = _LIST_PROPS[prop] 

1055 if isinstance(value, (str, bytes)) or isinstance(value, Mapping): 

1056 raise TypeError(f"{prop} must be an iterable of {what}, " 

1057 f"got {value!r}") 

1058 try: 

1059 items: tuple[object, ...] = tuple(cast("Iterable[object]", value)) 

1060 except TypeError: 

1061 raise TypeError(f"{prop} must be an iterable of {what}, " 

1062 f"got {value!r}") from None 

1063 words = [x for x in items if isinstance(x, str)] 

1064 if len(words) != len(items): 

1065 raise TypeError(f"{prop} entries must be strings, got " 

1066 f"{value!r}") 

1067 if prop in ("short_for", "spelling_of") and ( 

1068 not words or any(not _normalize(x) for x in words)): 

1069 # the build's check 3: each a given name, none empty 

1070 raise ValueError( 

1071 f"{prop} must be a non-empty list of given names, none " 

1072 f"normalizing to nothing, got {value!r}; write e.g. " 

1073 f"{prop}={['maxwell'] if prop == 'short_for' else ['olga']!r}") 

1074 folded = tuple(sorted({_normalize(x) for x in words} - {""})) 

1075 if prop in ("completed_by", "completes") and not folded: 

1076 # an empty list would leave `completes` unwritten, which 

1077 # joins behind ANY plain word, the widest reading; the build 

1078 # refuses it too (#1072) 

1079 cleared = ("joins it behind any plain word" 

1080 if prop == "completes" 

1081 else "leaves no listed word completing it") 

1082 raise ValueError(f"{prop} must list at least one word, got " 

1083 f"{value!r}; list the words it pairs with, or " 

1084 f"write {prop}=None to clear the list, which " 

1085 f"{cleared}") 

1086 if prop in ("completed_by", "completes") and any(" " in w for w in folded): 

1087 # rules/P12 joins two words: a bound word to the one word 

1088 # after it (completed_by), a bound_second word to the one 

1089 # before it (completes) 

1090 raise ValueError(f"{prop} entries must be single words, " 

1091 f"got {value!r}; list each word on its own") 

1092 if prop in ("short_for", "spelling_of") and any( 

1093 " " in w for w in folded): 

1094 # the match compares a given name word by word 

1095 raise ValueError(f"{prop} entries must be single given " 

1096 f"names, got {value!r}; list each on its own") 

1097 return folded or None 

1098 # same_as: the word this one is a listed spelling of, a given name 

1099 # written short's full name (#789) or a title's or suffix's full 

1100 # form, or several, as a list (`md` of four spellings of Muhammad, 

1101 # #1383); one is kept as its text, so an edit written before lists 

1102 # were taken is the same edit, and several as a sorted tuple 

1103 fix = "write e.g. same_as='muhammad' or same_as=['muhammad', 'mohammad']" 

1104 if isinstance(value, str): 

1105 if not value.strip(): 

1106 raise ValueError(f"same_as must name the word this one is a " 

1107 f"spelling of, got the empty text {value!r}; " 

1108 f"{fix}") 

1109 return value 

1110 if isinstance(value, (bytes, Mapping)) or not isinstance(value, Iterable): 

1111 raise TypeError(f"same_as must be the word this one is a spelling " 

1112 f"of, a string, or a list of them, got {value!r}; " 

1113 f"{fix}") 

1114 heads = tuple(cast("Iterable[object]", value)) 

1115 for h in heads: 

1116 if not isinstance(h, str): 

1117 raise TypeError(f"same_as entries must be strings, got {h!r} " 

1118 f"in {value!r}; {fix}") 

1119 if not heads or not all(cast("str", h).strip() for h in heads): 

1120 raise ValueError(f"same_as must name at least one word, none of " 

1121 f"them empty, got {value!r}; {fix}") 

1122 unique = tuple(sorted(set(cast("tuple[str, ...]", heads)))) 

1123 return unique[0] if len(unique) == 1 else unique 

1124 

1125 

1126def _carries(props: Mapping[str, Any], prop: str, value: object) -> bool: 

1127 """A reading's properties carry `prop` at `value`, canonical as 

1128 `_prop_value` writes it: equal, save `same_as`, which a reading may 

1129 hold as several words and which is carried where every word asked 

1130 is among them (#1383).""" 

1131 if prop != "same_as" or value is None: 

1132 return props.get(prop) == value 

1133 held = _index_module().same_as_of(props) 

1134 asked = _index_module().same_as_of({"same_as": value}) 

1135 return set(asked) <= set(held) 

1136 

1137 

1138def _check_kind(kind: object, op: str) -> str | None: 

1139 """`kind` checked for `op`: a kind, or on `remove` and `words` a 

1140 category too; None (every reading) only on `remove`.""" 

1141 ri = _index_module() 

1142 if kind is None and op == "remove": 

1143 return None 

1144 if not isinstance(kind, str): 

1145 raise TypeError(f"{op}() takes kind as a string, a vocabulary " 

1146 f"kind such as 'title' or 'credential', got " 

1147 f"{kind!r}") 

1148 if kind in ri.CATEGORY: 

1149 return kind 

1150 categories = set(ri.CATEGORY.values()) 

1151 if kind in categories: 

1152 if op in ("remove", "words"): 

1153 return kind 

1154 raise ValueError( 

1155 f"{kind!r} is a category with no kind of its name; add() " 

1156 f"takes one of its kinds: " + ", ".join( 

1157 k for k, c in ri.CATEGORY.items() if c == kind)) 

1158 raise ValueError( 

1159 f"unknown reading kind {kind!r}; the kinds are " 

1160 + ", ".join(ri.CATEGORY) 

1161 + (f" (or a category, on {op}: " 

1162 + ", ".join(sorted(categories)) + ")" 

1163 if op in ("remove", "words") else "")) 

1164 

1165 

1166def _edit_words(words: tuple[object, ...], op: str, 

1167 kind: str | None) -> tuple[str, ...]: 

1168 if not words: 

1169 if op == "remove" and kind is not None: 

1170 # every word's readings of `kind`: a remove of a whole kind, 

1171 # which `remove` writes only with every=True, so that an 

1172 # empty `remove(*words, kind=...)` never reaches it 

1173 return () 

1174 raise TypeError( 

1175 f"{op}() takes at least one word, e.g. {op}('dean', kind=" 

1176 f"'title')" + (", or every=True with a kind to take out every " 

1177 "word's readings of it, e.g. remove(kind=" 

1178 "'title', every=True)" if op == "remove" else "")) 

1179 out = [] 

1180 for w in words: 

1181 _reject_buffer(w, f"{op}() words", "strings") 

1182 if not isinstance(w, str): 

1183 raise TypeError( 

1184 f"{op}() takes each word as its own argument, a string, " 

1185 f"got {w!r}; unpack a collection: {op}(*words, kind=...)") 

1186 n = _title_key(w.split()) 

1187 if not n: 

1188 raise ValueError(f"{op}() word {w!r} normalizes to empty " 

1189 f"(lowercase + strip full stops/whitespace " 

1190 f"leaves nothing)") 

1191 out.append(n) 

1192 return tuple(out) 

1193 

1194 

1195def _edit_props(kind: str, props: Mapping[str, object]) -> _Props: 

1196 ri = _index_module() 

1197 allowed = ri.indexed(kind) - _UNSTATED 

1198 if kind == "family": 

1199 # a name category's property that only a given name takes: the 

1200 # raise below names it, so the generic message leaves it out 

1201 allowed -= {"after_particle"} 

1202 out: dict[str, object] = {} 

1203 for prop, value in props.items(): 

1204 if prop == "default": 

1205 raise ValueError( 

1206 "add() takes no default: a caller's reading is on, which " 

1207 "is the caller's choice; take one out with remove(word, " 

1208 "kind=...)") 

1209 if prop == "cased": 

1210 raise ValueError( 

1211 "add() takes no cased: a case mask is configured through " 

1212 "capitalization_exceptions, e.g. dataclasses.replace(" 

1213 "lexicon, capitalization_exceptions=(*lexicon." 

1214 "capitalization_exceptions, ('phd', 'PhD')))") 

1215 if prop == "after_particle" and kind == "family": 

1216 raise ValueError( 

1217 "after_particle names a given name written behind a " 

1218 "particle (rules/P10), so only a given reading takes it: " 

1219 "write add(word, kind='given', after_particle=True)") 

1220 if prop not in allowed: 

1221 raise ValueError( 

1222 f"{_a(kind)} {kind} reading takes " 

1223 + (", ".join(sorted(allowed)) or "no properties") 

1224 + f"; got {prop!r}") 

1225 out[prop] = _prop_value(kind, prop, value) 

1226 return tuple(sorted(out.items())) 

1227 

1228 

1229def _make_edit(op: object, words: object, kind: object, 

1230 props: object) -> _Edit: 

1231 """An edit checked and canonical: what `add` and `remove` store and 

1232 what a constructor's `_edits` must already be.""" 

1233 if op not in ("add", "remove"): 

1234 raise ValueError(f"an edit is 'add' or 'remove', got {op!r}") 

1235 if not isinstance(words, tuple): 

1236 raise TypeError(f"an edit's words are a tuple, got {words!r}") 

1237 k = _check_kind(kind, op) 

1238 ws = _edit_words(words, op, k) 

1239 if op == "remove": 

1240 return _Edit(op, ws, k, _removed_pairs(k, ws, props)) 

1241 assert k is not None 

1242 if not isinstance(props, (tuple, Mapping)): 

1243 raise TypeError(f"an edit's properties are pairs, got {props!r}") 

1244 p = _edit_props(k, dict(props)) 

1245 ri = _index_module() 

1246 category = ri.CATEGORY[k] 

1247 if category in _MATCHING_LISTS: 

1248 # the build's check 3: a familiar reading lists the longer names, 

1249 # a spelling the names it is another spelling of 

1250 prop = _MATCHING_LISTS[category] 

1251 names = dict(p).get(prop) 

1252 if not names: 

1253 raise ValueError( 

1254 f"a {category} reading needs {prop}, a non-empty list of " 

1255 f"given names, e.g. {_MATCHING_EXAMPLES[category]}") 

1256 for w in ws: 

1257 if w in names: 

1258 raise ValueError( 

1259 f"{prop} names the word itself, {w!r}; it lists the " 

1260 f"other given names") 

1261 for w in ws: 

1262 # the build's check 8: a phrase is matched whole only as a birth 

1263 # marker or a run of titles addressing the given name 

1264 if " " in w and not (k == "birth_marker" or ( 

1265 category == "title" and ("addresses", "given") in p)): 

1266 raise ValueError( 

1267 f"{w!r} is a phrase, which can never match as {_a(k)} {k}: only " 

1268 f"a birth_marker and a title with addresses='given' are " 

1269 f"matched as a whole run; add its words one by one") 

1270 # the build refuses attached on a title phrase: the glued-title 

1271 # peel splits one word (rules/W6) 

1272 if " " in w and category == "title" and ("attached", "before") in p: 

1273 raise ValueError( 

1274 f"{w!r} is a phrase; attached='before' marks a one-word " 

1275 f"title that the glued-title peel splits off a word") 

1276 # the build refuses may_be_initial on anything but a cased single 

1277 # letter: no other word reads as an initial (rules/P8) 

1278 if ("may_be_initial", True) in p and not ( 

1279 len(w) == 1 and w.upper() != w.lower()): 

1280 raise ValueError( 

1281 f"may_be_initial marks a single cased letter that may read " 

1282 f"as an initial; {w!r} is not one") 

1283 return _Edit(op, ws, k, p) 

1284 

1285 

1286def _refuse_unpaired(props: Iterable[str]) -> None: 

1287 """Raise for a keyword `remove` does not take: any but the two pair 

1288 lists, which only a `familiar` or a `spelling` remove names.""" 

1289 for prop in props: 

1290 if prop not in _MATCHING_LISTS.values(): 

1291 ri = _index_module() 

1292 known = any(prop in ri.indexed(k) for k in ri.CATEGORY) 

1293 raise TypeError( 

1294 f"remove() got an unexpected keyword argument {prop!r}: it " 

1295 f"takes a property only as the pairs to drop from a " 

1296 f"familiar or a spelling reading, " 

1297 + " or ".join(_MATCHING_REMOVALS.values()) 

1298 + (f"; to take {prop} off a reading, add() it with its " 

1299 f"unwritten value, add(word, kind=..., {prop}=None)" 

1300 if known and prop not in _UNSTATED else "")) 

1301 

1302 

1303def _removed_pairs(kind: str | None, words: tuple[str, ...], 

1304 props: object) -> _Props: 

1305 """A remove's properties checked and canonical: none, or the one 

1306 list a `familiar` or `spelling` remove names its pairs by 

1307 (`short_for`, `spelling_of`), the names normalized and sorted as an 

1308 add's are (decisions/name-matching, 2026-11-15 #1404). A name that 

1309 is one of the words is kept: the pair of a word with itself is in 

1310 no lexicon, and removing what is absent is no error.""" 

1311 if not props: 

1312 return () 

1313 if not isinstance(props, (tuple, Mapping)): 

1314 raise TypeError(f"an edit's properties are pairs, got {props!r}") 

1315 given: dict[str, object] = dict(props) 

1316 _refuse_unpaired(given) 

1317 own = _MATCHING_LISTS.get(kind) if kind is not None else None 

1318 for prop in given: 

1319 if prop != own: 

1320 holder = next(k for k, p in _MATCHING_LISTS.items() if p == prop) 

1321 raise ValueError( 

1322 f"{prop} names the pairs of a {holder} reading, and this " 

1323 f"remove() is of kind={kind!r}; write " 

1324 f"{_MATCHING_REMOVALS[holder]}") 

1325 assert kind is not None and own is not None 

1326 if not words: 

1327 raise TypeError( 

1328 f"remove(every=True) takes out every {kind} reading and takes " 

1329 f"no {own}; name the words of the pairs to drop: " 

1330 f"{_MATCHING_REMOVALS[kind]}") 

1331 names = _prop_value(kind, own, given[own]) 

1332 if names is None: 

1333 raise ValueError( 

1334 f"{own} must be a non-empty list of given names, got " 

1335 f"{given[own]!r}; write {_MATCHING_REMOVALS[kind]}, or leave " 

1336 f"{own} out to drop every pair naming the word") 

1337 return ((own, names),) 

1338 

1339 

1340@functools.lru_cache(maxsize=1 << 15) 

1341def _name_keys(name: str) -> frozenset[str]: 

1342 # kept per name: a remove of pairs asks it of every listed name of 

1343 # the kind, once per edit of a log that every new edit replays 

1344 return frozenset(k for k in {name} | _forms(name) if k) 

1345 

1346 

1347def _pair_keys(names: Iterable[str]) -> frozenset[str]: 

1348 """What the familiar-form index files `names` under (`_familiar_of`): 

1349 each as stored and in every folded form (`_forms`). Two names are 

1350 one name to the match where their keys meet.""" 

1351 return frozenset(k for n in names for k in _name_keys(n)) 

1352 

1353 

1354#: Per matching-only kind, a key (`_name_keys`) -> the words that may 

1355#: hold a pair naming it: one build's index for its removes of pairs, 

1356#: made at the first and kept a superset after it (an add joins it, a 

1357#: remove leaves its entries), so a log of many removes scans the pool 

1358#: once and not once per edit. 

1359_PairIndex = dict[str, dict[str, set[str]]] 

1360 

1361 

1362def _index_pairs(index: dict[str, set[str]], word: str, 

1363 names: Iterable[str]) -> None: 

1364 for name in (word, *names): 

1365 for key in _name_keys(name): 

1366 index.setdefault(key, set()).add(word) 

1367 

1368 

1369def _drop_pairs(pool: dict[str, tuple[Any, ...]], edit: _Edit, 

1370 index: _PairIndex) -> tuple[str, ...]: 

1371 """Apply a `familiar` or `spelling` remove of words to `pool` in 

1372 place, returning the words it touched. A pair is stored on one of 

1373 its two words and read both ways, so the remove reaches both 

1374 (decisions/name-matching, 2026-11-15 #1404): with no names, every 

1375 pair naming one of the words goes, the word's own readings of the 

1376 kind and its name in every other word's list; with names, each 

1377 pair of a word and a name goes, whichever of the two holds it. 

1378 A name is compared as the match reads it, by its folded forms 

1379 (`_pair_keys`), so a pair stored accented (`álex`) goes with the 

1380 word written plain, which the match would otherwise still read it 

1381 for. Every file's reading of the pair is cut, one written `default 

1382 = false` too, and keeps its file and whether it is on; a reading 

1383 left listing no name goes with its last one.""" 

1384 assert edit.kind is not None 

1385 prop = _MATCHING_LISTS[edit.kind] 

1386 words = _pair_keys(edit.words) 

1387 listed = dict(edit.props).get(prop) 

1388 names = None if listed is None else _pair_keys(listed) 

1389 held_by = index.get(edit.kind) 

1390 if held_by is None: 

1391 held_by = index[edit.kind] = {} 

1392 for w, rs in pool.items(): 

1393 for r in rs: 

1394 if r.kind == edit.kind: 

1395 _index_pairs(held_by, w, r.props.get(prop, ())) 

1396 ri = _index_module() 

1397 touched = [] 

1398 for w in sorted({w for key in words | (names or frozenset()) 

1399 for w in held_by.get(key, ())}): 

1400 rs = pool.get(w, ()) 

1401 mine = _name_keys(w) 

1402 # the names to cut from this word's lists: the words', where it 

1403 # is not one of them (every name where it is, and no names were 

1404 # given); under names, the names' where it is a word and the 

1405 # words' where it is a name 

1406 if names is None: 

1407 cut = None if not mine.isdisjoint(words) else words 

1408 else: 

1409 cut = ((names if not mine.isdisjoint(words) else frozenset()) 

1410 | (words if not mine.isdisjoint(names) else frozenset())) 

1411 if not cut: 

1412 continue 

1413 kept = [] 

1414 for r in rs: 

1415 if r.kind != edit.kind: 

1416 kept.append(r) 

1417 elif cut is not None: 

1418 held = r.props.get(prop, ()) 

1419 left = tuple(n for n in held 

1420 if _name_keys(n).isdisjoint(cut)) 

1421 if len(left) == len(held): 

1422 kept.append(r) 

1423 elif left: 

1424 kept.append(ri.IndexReading( 

1425 w, r.tag, r.kind, 

1426 MappingProxyType({**r.props, prop: left}))) 

1427 if len(kept) == len(rs) and all(x is y for x, y in zip(kept, rs)): 

1428 continue 

1429 touched.append(w) 

1430 if kept: 

1431 pool[w] = tuple(kept) 

1432 else: 

1433 del pool[w] 

1434 return tuple(touched) 

1435 

1436 

1437def _extend_pairs(pool: dict[str, tuple[Any, ...]], edit: _Edit, 

1438 index: _PairIndex) -> tuple[str, ...]: 

1439 """Apply a `familiar` or `spelling` add to `pool` in place, 

1440 returning its words. It EXTENDS: the caller's names go in a reading 

1441 of the caller's own, attributed to the edit and to no file, and the 

1442 compile unions it with each file's, which stay as they are 

1443 (decisions/name-matching, 2026-11-08 FAMILIAR FORMS); an explicit 

1444 replace is remove, then add.""" 

1445 assert edit.kind is not None 

1446 ri = _index_module() 

1447 prop = _MATCHING_LISTS[edit.kind] 

1448 for w in edit.words: 

1449 rs = pool.get(w, ()) 

1450 added = set(dict(edit.props)[prop]) 

1451 if edit.kind in index: 

1452 _index_pairs(index[edit.kind], w, added) 

1453 mine = [r for r in rs if r.kind == edit.kind and not r.tag] 

1454 if mine: 

1455 added |= set(mine[0].props.get(prop, ())) 

1456 reading = ri.IndexReading(w, "", edit.kind, MappingProxyType( 

1457 {prop: tuple(sorted(added))})) 

1458 pool[w] = tuple(r for r in rs if r not in mine) + (reading,) 

1459 return edit.words 

1460 

1461 

1462def _apply_edit(pool: dict[str, tuple[Any, ...]], edit: _Edit, 

1463 index: _PairIndex) -> tuple[str, ...]: 

1464 """Apply `edit` to `pool` (word -> its readings) in place, returning 

1465 the words it touched. An add of a kind the word holds updates that 

1466 reading's properties in every file holding it, and turns a reading 

1467 written `default = false` on; otherwise it adds the caller's own 

1468 reading, which names no file. A remove with no words is one of a 

1469 whole kind, reaching every word in the pool that holds a reading of 

1470 it, whatever turned the reading on. An add or a remove of words' 

1471 `familiar` or `spelling` readings is one of pairs (`_extend_pairs`, 

1472 `_drop_pairs`).""" 

1473 if edit.words and edit.kind in _MATCHING_LISTS: 

1474 return (_drop_pairs if edit.op == "remove" else _extend_pairs)( 

1475 pool, edit, index) 

1476 ri = _index_module() 

1477 words = edit.words or tuple( 

1478 w for w, rs in pool.items() 

1479 if any(r.kind == edit.kind or r.category == edit.kind for r in rs)) 

1480 for w in words: 

1481 rs = pool.get(w, ()) 

1482 if edit.op == "remove": 

1483 kept = tuple(r for r in rs if edit.kind is not None 

1484 and r.kind != edit.kind and r.category != edit.kind) 

1485 elif any(r.kind == edit.kind for r in rs): 

1486 kept = tuple( 

1487 ri.IndexReading(w, r.tag, r.kind, MappingProxyType( 

1488 _merged(r.props, edit.props))) 

1489 if r.kind == edit.kind else r for r in rs) 

1490 else: 

1491 kept = rs + (ri.IndexReading(w, "", edit.kind, MappingProxyType( 

1492 {k: v for k, v in edit.props if v is not None})),) 

1493 if kept: 

1494 pool[w] = kept 

1495 else: 

1496 pool.pop(w, None) 

1497 return words 

1498 

1499 

1500def _merged(props: Mapping[str, Any], update: _Props) -> dict[str, Any]: 

1501 out = {k: v for k, v in props.items() if k != "default"} 

1502 for k, v in update: 

1503 if v is None: 

1504 out.pop(k, None) 

1505 else: 

1506 out[k] = v 

1507 return out 

1508 

1509 

1510Pool = Mapping[str, tuple[Any, ...]] 

1511 

1512 

1513@functools.lru_cache(maxsize=8) 

1514def _base_pool(base: object) -> Pool: 

1515 """A base's readings by word, on by default or not: the shipped 

1516 index for `"default"`, none for `"empty"`, a snapshot's own rows.""" 

1517 if base == "empty": 

1518 return MappingProxyType({}) 

1519 ri = _index_module() 

1520 if base == "default": 

1521 # the readings `index()` keeps, so a lexicon under a choice, 

1522 # which compiles from them too, holds one copy 

1523 return MappingProxyType({ 

1524 text: tuple(rs) for text, rs in itertools.groupby( 

1525 ri.index(), key=lambda r: r.text)}) 

1526 return MappingProxyType({ 

1527 text: tuple(ri.from_row(text, row) for row in rs) 

1528 for text, rs in cast("Iterable[tuple[str, Any]]", base)}) 

1529 

1530 

1531def _check_pool(pool: Pool, w: str) -> None: 

1532 """The build's checks a caller's edits can reach, over a word they 

1533 touch (checks 3 and 8 run per edit, in _make_edit): one suffix 

1534 kind per word (check 4), an agnomen has a name reading (check 11's 

1535 agnomen clause), and a bound given name that is also a particle has 

1536 a given reading (check 9).""" 

1537 on = [r for r in pool.get(w, ()) if r.on_by_default] 

1538 suffix = {r.kind: r for r in on if r.category == "suffix"} 

1539 if len(suffix) > 1: 

1540 held = sorted(k for k, r in suffix.items() if r.tag) 

1541 drop = held[0] if held else sorted(suffix)[0] 

1542 raise ValueError( 

1543 f"{w!r} would hold two suffix kinds, " 

1544 f"{' and '.join(sorted(suffix))}, and a word holds one; " 

1545 f"remove the one it holds first: .remove({w!r}, " 

1546 f"kind={drop!r})") 

1547 kinds = {r.category for r in on} | {r.kind for r in on} 

1548 # check 11's agnomen clause: an agnomen is written in the case of 

1549 # the name around it, so only the count gates it, and the gate is 

1550 # a name reading beside it (rules/S11), one that marks a clash (a 

1551 # given name written short gates nothing, #1383) 

1552 if "agnomen" in kinds and not any(r.marks_a_clash for r in on): 

1553 raise ValueError( 

1554 f"{w!r} is an agnomen with no name reading that gates it, " 

1555 f"and an agnomen is read as the suffix only where a name " 

1556 f"reading gates it by the count (a given name written " 

1557 f"short, carrying same_as, gates nothing): write " 

1558 f".add({w!r}, kind='family') first, then the agnomen") 

1559 if {"bound_given", "particle"} <= kinds and "given" not in kinds: 

1560 raise ValueError( 

1561 f"{w!r} is a bound given name and a particle with no given " 

1562 f"reading, and a particle that never starts a given name " 

1563 f"cannot bind one: .add({w!r}, kind='given'), or " 

1564 f".remove({w!r}, kind='bound_given')") 

1565 

1566 

1567@functools.lru_cache(maxsize=32) 

1568def _chosen_pool(base: object, chosen: frozenset[str], strict: bool) -> Pool: 

1569 """A base's readings under the choice of the file tags `chosen`, 

1570 before the caller's edits (decisions/vocabulary-model, 2026-11-02 

1571 #754, item 4): `choose` over the base's readings, under `strict` 

1572 only the chosen files', mul.toml's and native-script ones; a 

1573 reading an 

1574 unchosen file leaves off stays in the pool off, so a caller's add 

1575 of its kind still turns it on, as it does with no choice.""" 

1576 pool = _base_pool(base) 

1577 if not chosen: 

1578 return pool 

1579 ri = _index_module() 

1580 readings = [r for rs in pool.values() for r in rs] 

1581 if strict: 

1582 readings = ri.strict_kept(readings, chosen) 

1583 out: dict[str, list[Any]] = {} 

1584 for r in ri.choose(readings, chosen): 

1585 out.setdefault(r.text, []).append(r) 

1586 for r in readings: 

1587 if not r.on_by_default and r.tag not in chosen: 

1588 out.setdefault(r.text, []).append(r) 

1589 return MappingProxyType({t: tuple(rs) for t, rs in out.items()}) 

1590 

1591 

1592@functools.lru_cache(maxsize=128) 

1593def _built(base: object, edits: tuple[_Edit, ...], chosen: frozenset[str], 

1594 strict: bool) -> tuple[Pool, Mapping[str, frozenset[str]], 

1595 SameAs, SameAsNamed, Familiar, Familiar]: 

1596 """A lexicon's readings by word and the sets they compile to, kept 

1597 per base, log and choice: a compile costs milliseconds, paid once 

1598 per configuration (decisions/vocabulary-model, 2026-11-01 #754). 

1599 The choice filters the base's readings and the log applies after 

1600 it, so a caller's reading survives any choice; one that clashes 

1601 with a reading the choice turns on is refused, naming the edit 

1602 (2026-11-02 #754, item 3).""" 

1603 pool = dict(_chosen_pool(base, chosen, strict)) 

1604 index: _PairIndex = {} 

1605 touched = [(edit, _apply_edit(pool, edit, index)) for edit in edits] 

1606 for w in dict.fromkeys(w for _, ws in touched for w in ws): 

1607 try: 

1608 _check_pool(pool, w) 

1609 except ValueError as exc: 

1610 if not chosen or _clashes_unchosen(base, edits): 

1611 raise 

1612 mine = " and ".join(_rendered(e for e, ws in touched if w in ws)) 

1613 raise ValueError( 

1614 f"the lexicon's {mine} clashes with a reading the choice " 

1615 f"turns on: {exc}") from None 

1616 ri = _index_module() 

1617 try: 

1618 compiled = ri.compile_readings( 

1619 r for rs in pool.values() for r in rs) 

1620 except ri.CompileError as exc: 

1621 raise ValueError(str(exc)) from None 

1622 return (MappingProxyType(pool), *_compiled_of(compiled)) 

1623 

1624 

1625def _clashes_unchosen(base: object, edits: tuple[_Edit, ...]) -> bool: 

1626 """Whether `edits` clash on `base` with no choice, so that a clash 

1627 under one is the log's own rather than the choice's.""" 

1628 try: 

1629 _built(base, edits, frozenset(), False) 

1630 except ValueError: 

1631 return True 

1632 return False 

1633 

1634 

1635def _compiled_for(base: object, edits: tuple[_Edit, ...], 

1636 chosen: frozenset[str], strict: bool) -> _Compiled: 

1637 if not edits and base == "default": 

1638 # under a choice, the shipped index compiled once per choice by 

1639 # the reader every pack shares 

1640 return (_choice_compiled(chosen, strict) if chosen 

1641 else _default_compiled()) 

1642 if not edits and not chosen and base == "empty": 

1643 return _NOTHING_COMPILED 

1644 return _built(base, edits, chosen, strict)[1:] 

1645 

1646 

1647@functools.lru_cache(maxsize=32) 

1648def _choice_compiled(chosen: frozenset[str], strict: bool) -> _Compiled: 

1649 ri = _index_module() 

1650 return _compiled_of(ri.compile_choice(chosen, strict)) 

1651 

1652 

1653class _ReadingFiles: 

1654 """The files whose readings are on in one lexicon, by word: what 

1655 ``Reading.languages`` names (decisions/vocabulary-model, 2026-11-02 

1656 #754, sub-phase 4i-d). One per base, log and choice 

1657 (`_reading_files`), held by each `Lexicon` it describes and never 

1658 pickled; it hashes by identity, in C, so assemble's memo keyed by 

1659 it costs no frame on a hit. 

1660 

1661 The default answers from the reading index's rows 

1662 (`_reading_index.languages_of`), and a choice with no log from the 

1663 word's own rows under `choose`, which is exact because a choice's 

1664 preference is per word; neither builds the lexicon's whole pool, 

1665 which a log or a snapshot base has built already, at construction.""" 

1666 

1667 __slots__ = ("_base", "_edits", "_chosen", "_strict") 

1668 

1669 def __init__(self, base: object, edits: tuple[_Edit, ...], 

1670 chosen: frozenset[str], strict: bool) -> None: 

1671 self._base, self._edits = base, edits 

1672 self._chosen, self._strict = chosen, strict 

1673 

1674 def pool(self) -> Pool: 

1675 """The lexicon's readings by word (`Lexicon._pool`).""" 

1676 if not self._edits: 

1677 return _chosen_pool(self._base, self._chosen, self._strict) 

1678 return _built(self._base, self._edits, self._chosen, 

1679 self._strict)[0] 

1680 

1681 def languages(self, text: str, kinds: frozenset[str]) -> tuple[str, ...]: 

1682 """The tags of the files holding a reading of `text` (as the 

1683 vocabulary stores it) of one of `kinds`, on in this lexicon, 

1684 sorted; a caller's own reading names none.""" 

1685 readings: Iterable[Any] 

1686 if self._edits or self._base not in ("default", "empty"): 

1687 readings = self.pool().get(text, ()) 

1688 elif self._base == "empty": 

1689 return () 

1690 else: 

1691 ri = _index_module() 

1692 if not self._chosen: 

1693 tags: tuple[str, ...] = ri.languages_of(text, kinds) 

1694 return tags 

1695 readings = ri.chosen_readings(ri.readings_of(text), self._chosen, 

1696 self._strict) 

1697 return tuple(sorted({r.tag for r in readings 

1698 if r.tag and r.kind in kinds 

1699 and r.on_by_default})) 

1700 

1701 

1702@functools.lru_cache(maxsize=128) 

1703def _reading_files(base: object, edits: tuple[_Edit, ...], 

1704 chosen: frozenset[str], strict: bool) -> _ReadingFiles: 

1705 # one per configuration, so equal lexicons share assemble's memo 

1706 return _ReadingFiles(base, edits, chosen, strict) 

1707 

1708 

1709def _check_choice(languages: object, strict: object) -> tuple[ 

1710 frozenset[str], frozenset[str]]: 

1711 """A recorded choice validated as `parser_for` validates one: its 

1712 languages in canonical case and the file tags they select, the 

1713 selection raising for a tag no file serves (decisions/ 

1714 vocabulary-model, 2026-11-02 #754, item 3).""" 

1715 if not isinstance(strict, bool): 

1716 raise TypeError(f"_strict must be True or False, got {strict!r}") 

1717 if (isinstance(languages, (str, bytes, bytearray, Mapping)) 

1718 or not isinstance(languages, Iterable)): 

1719 raise TypeError(f"_languages must be a set of BCP 47 tags, e.g. " 

1720 f"frozenset({{'pt'}}), got {languages!r}") 

1721 tags = frozenset(cast("Iterable[object]", languages)) 

1722 for tag in tags: 

1723 if not isinstance(tag, str): 

1724 raise TypeError(f"_languages entries must be str BCP 47 tags, " 

1725 f"got {tag!r}") 

1726 if not tags: 

1727 if strict: 

1728 raise ValueError( 

1729 "a strict choice keeps only the chosen languages' " 

1730 "vocabulary and the shared words (mul.toml), and " 

1731 "_languages chooses none; choose through " 

1732 "parser_for(..., strict=True) with a pack that chooses one") 

1733 return frozenset(), frozenset() 

1734 canon = frozenset(_canonical(cast(str, t)) for t in tags) 

1735 return canon, _index_module().selected(canon, strict=strict) 

1736 

1737 

1738def _canonical(tag: str) -> str: 

1739 """`tag` in BCP 47's canonical case: the language subtag lowercase, 

1740 a four-letter script subtag title case, a two-letter region 

1741 uppercase, every other subtag lowercase (RFC 5646, 2.1.1). Equal 

1742 choices then compare and hash equal, whatever case they were 

1743 written in.""" 

1744 first, *rest = tag.split("-") 

1745 out = [first.lower()] 

1746 for sub in rest: 

1747 if len(sub) == 4 and sub.isalpha(): 

1748 out.append(sub.title()) 

1749 elif len(sub) == 2 and sub.isalpha(): 

1750 out.append(sub.upper()) 

1751 else: 

1752 out.append(sub.lower()) 

1753 return "-".join(out) 

1754 

1755 

1756#: The most tags a repr lists (a `Lexicon`'s choice, a `Locale`'s); a 

1757#: longer choice is shown by its size, so the repr stays bounded however 

1758#: many languages are chosen. 

1759_REPR_TAGS = 3 

1760 

1761 

1762def _shown_choice(languages: frozenset[str]) -> str: 

1763 if len(languages) > _REPR_TAGS: 

1764 return f"languages: {len(languages)}" 

1765 return "languages " + "+".join(sorted(languages)) 

1766 

1767 

1768def _check_base(base: object) -> object: 

1769 """`"default"`, `"empty"`, or a snapshot of index rows from a pickle 

1770 (decisions/vocabulary-model, 2026-11-02 #754, items 3 and 5), which 

1771 becomes `"default"` where it is the running release's index.""" 

1772 if base in ("default", "empty"): 

1773 return base 

1774 if not isinstance(base, tuple): 

1775 raise TypeError(f"a Lexicon's base is 'default', 'empty' or a " 

1776 f"snapshot of index rows, got {base!r}") 

1777 ri = _index_module() 

1778 from nameparser.config._index import READINGS 

1779 if base == READINGS: 

1780 return "default" 

1781 shape = ("a Lexicon snapshot is (word, rows) pairs, each row (tag, " 

1782 "kind, properties), the properties (name, value) pairs") 

1783 for entry in base: 

1784 if not (isinstance(entry, tuple) and len(entry) == 2 

1785 and isinstance(entry[0], str) 

1786 and isinstance(entry[1], tuple)): 

1787 raise TypeError(f"{shape}; got {entry!r}") 

1788 word, rows = entry 

1789 for row in rows: 

1790 if not (isinstance(row, tuple) and len(row) == 3): 

1791 raise TypeError(f"{shape}; {word!r} has the row {row!r}") 

1792 tag, kind, pairs = row 

1793 if not isinstance(tag, str) or not isinstance(kind, str): 

1794 raise TypeError(f"{shape}, the tag and the kind strings; " 

1795 f"{word!r} has the row {row!r}") 

1796 if kind not in ri.CATEGORY: 

1797 raise ValueError( 

1798 f"a Lexicon snapshot holds the reading kind {kind!r}, " 

1799 f"which this release does not know") 

1800 if not isinstance(pairs, tuple) or not all( 

1801 isinstance(p, tuple) and len(p) == 2 

1802 and isinstance(p[0], str) for p in pairs): 

1803 raise TypeError(f"{shape}; {word!r} has the row {row!r}") 

1804 for name, value in pairs: 

1805 if name not in ri.indexed(kind): 

1806 raise ValueError( 

1807 f"a Lexicon snapshot gives {word!r}'s {kind} reading " 

1808 f"the property {name!r}, which {_a(kind)} {kind} reading " 

1809 f"does not take in this release") 

1810 try: 

1811 hash(value) 

1812 except TypeError: 

1813 raise TypeError( 

1814 f"a Lexicon snapshot gives {word!r}'s {kind} reading " 

1815 f"{name}={value!r}; a value is a string, a bool or " 

1816 f"a tuple") from None 

1817 return base 

1818 

1819 

1820@functools.cache 

1821def _choice_masks(chosen: frozenset[str], strict: bool) -> tuple[ 

1822 frozenset[str], tuple[tuple[str, str], ...]]: 

1823 """The case masks the choice of the file tags `chosen` moves against 

1824 the default's compile: the ones that leave and the ones set. A mask 

1825 is no reading (a `Lexicon` keeps its masks in a field of their own), 

1826 so `parser_for` moves them in that field, as 3b's delta did.""" 

1827 ri = _index_module() 

1828 old = ri.compile_choice(frozenset())["CAPITALIZATION_EXCEPTIONS"] 

1829 new = ri.compile_choice(chosen, strict)["CAPITALIZATION_EXCEPTIONS"] 

1830 return (frozenset(old.keys() - new.keys()), 

1831 tuple(sorted((k, v) for k, v in new.items() if old.get(k) != v))) 

1832 

1833 

1834def _rechosen_masks(lexicon: Lexicon, chosen: frozenset[str], 

1835 strict: bool) -> tuple[tuple[str, str], ...]: 

1836 """`lexicon`'s masks moved from its own choice's to `chosen`'s: the 

1837 base's choice's moves undone, then the new choice's applied, so a 

1838 chained choice moves them as the union does.""" 

1839 cap = dict(lexicon.capitalization_exceptions) 

1840 if lexicon.languages: 

1841 default = _index_module().compile_choice( 

1842 frozenset())["CAPITALIZATION_EXCEPTIONS"] 

1843 gone, joined = _choice_masks(lexicon._chosen, lexicon.strict) 

1844 for k in gone: 

1845 cap.setdefault(k, default[k]) 

1846 for k, v in joined: 

1847 if cap.get(k) == v: 

1848 if k in default: 

1849 cap[k] = default[k] 

1850 else: 

1851 del cap[k] 

1852 gone, joined = _choice_masks(chosen, strict) 

1853 for k in gone: 

1854 cap.pop(k, None) 

1855 cap.update(joined) 

1856 return tuple(sorted(cap.items())) 

1857 

1858 

1859def _fields_of(sets: _LexiconSets | Mapping[str, frozenset[str]], 

1860 ) -> dict[str, frozenset[str]]: 

1861 get = (sets.__getitem__ if isinstance(sets, Mapping) 

1862 else functools.partial(getattr, sets)) 

1863 return {f: get(f) for f in _SET_FIELDS + _KIND_FIELDS} 

1864 

1865 

1866def _rendered(edits: Iterable[_Edit]) -> list[str]: 

1867 """Edits as the calls that make them, consecutive ones of one kind 

1868 and properties joined into one call.""" 

1869 calls: list[tuple[str, list[str], str | None, _Props]] = [] 

1870 for e in edits: 

1871 # a remove of a whole kind (no words) joins no call of words 

1872 if (calls and e.words and calls[-1][1] 

1873 and calls[-1][0] == e.op 

1874 and calls[-1][2:] == (e.kind, e.props)): 

1875 calls[-1][1].extend(e.words) 

1876 else: 

1877 calls.append((e.op, list(e.words), e.kind, e.props)) 

1878 out = [] 

1879 for op, words, kind, props in calls: 

1880 args = [repr(w) for w in words] 

1881 if kind is not None: 

1882 args.append(f"kind={kind!r}") 

1883 args += [f"{k}={_shown_value(kind, k, v)}" for k, v in props] 

1884 if op == "remove" and not words: 

1885 args.append("every=True") 

1886 out.append(f".{op}({', '.join(args)})") 

1887 return out 

1888 

1889 

1890def _shown_value(kind: str | None, prop: str, value: object) -> str: 

1891 """A logged property value as a caller writes it: a removed one as 

1892 its unwritten value where it has one (`may_be_initial=False`).""" 

1893 if value is None and kind is not None and ( 

1894 prop in _FLAG_PROPS or prop == "addresses"): 

1895 value = _unwritten(kind, prop) 

1896 if isinstance(value, tuple) and len(value) > _SHOWN_WORDS: 

1897 # bounded: a reading's list may name every title word it 

1898 # reaches 

1899 return (repr(list(value[:_SHOWN_WORDS]))[:-1] 

1900 + f", ... {len(value) - _SHOWN_WORDS} more]") 

1901 return repr(list(value) if isinstance(value, tuple) else value) 

1902 

1903 

1904#: The most words a clash message shows of one property's list. 

1905_SHOWN_WORDS = 6 

1906 

1907 

1908def _refusal(where: str, removed: Mapping[str, object]) -> TypeError: 

1909 """The TypeError for a 2.x spelling: a list or the masks with the 

1910 call that changes them, a set field with docs/migrate.rst's table, 

1911 which names the kind of each (decisions/vocabulary-model, 

1912 2026-11-08 #1003).""" 

1913 unknown = [k for k in removed if k not in _2X_FIELDS] 

1914 if unknown: 

1915 return TypeError(f"{where} got an unexpected keyword argument " 

1916 f"{unknown[0]!r}") 

1917 if "capitalization_exceptions" in removed: 

1918 return TypeError( 

1919 "capitalization_exceptions holds key->value pairs; use " 

1920 "dataclasses.replace(lexicon, capitalization_exceptions=(*lexicon." 

1921 "capitalization_exceptions, ('key', 'KEY'))) instead of " 

1922 f"{where}") 

1923 lists = [k for k in removed if k in _LIST_FIELDS] 

1924 if lists: 

1925 name = lists[0] 

1926 given = removed[name] 

1927 words = (sorted(given) if isinstance(given, Iterable) 

1928 and not isinstance(given, (str, bytes, Mapping)) 

1929 and all(isinstance(w, str) for w in given) and given 

1930 else ["word"]) 

1931 shown = "{" + ", ".join(map(repr, words)) + "}" 

1932 code = (f"dataclasses.replace(lexicon, {name}=lexicon.{name} - " 

1933 f"{shown})" if where.startswith("remove") 

1934 else f"lexicon | Lexicon({name}={shown})") 

1935 return TypeError( 

1936 f"{name} is a list, changed with a fragment since 3.0, not " 

1937 f"{where}: write {code}") 

1938 return TypeError( 

1939 f"{where} takes no {', '.join(removed)} since 3.0: a Lexicon is " 

1940 f"configured by reading, add(*words, kind=..., **properties) and " 

1941 f"remove(*words, kind=...); docs/migrate.rst's Lexicon table " 

1942 f"gives the kind for each 2.x field") 

1943 

1944 

1945def _refuse_2x(where: str, keywords: Mapping[str, object]) -> None: 

1946 """Raise `_refusal` where `keywords` name a 2.x field.""" 

1947 old = {k: v for k, v in keywords.items() if k in _2X_FIELDS} 

1948 if old: 

1949 raise _refusal(where, old) 

1950 

1951 

1952#: The keys of the one 2.x `Lexicon` layout 3.0 loaded, 2.7's and 

1953#: 2.8's, read off a 2.8.0 `Lexicon.default()` state; 3.0 admitted 

1954#: `given_names` beside them. A record of what shipped, so it never 

1955#: follows `_VOCAB_FIELDS`, which a new vocabulary field joins. 

1956_LAYOUT_3_0_LOADED = frozenset({ 

1957 "after_given_titles", "agnomens", "bound_given_names", 

1958 "capitalization_exceptions", "conjunctions", "conjunctions_ambiguous", 

1959 "given_name_abbreviations", "given_name_titles", "honorific_tails", 

1960 "maiden_markers", "particles", "particles_ambiguous", "suffix_acronyms", 

1961 "suffix_acronyms_ambiguous", "suffix_words", "suffix_words_ambiguous", 

1962 "surnames", "title_modifiers", "title_phrases", "title_styles", 

1963 "titles", "titles_ambiguous"}) 

1964 

1965 

1966def _refused_2x(state: Mapping[str, object]) -> ValueError: 

1967 """The ValueError for a 2.x `Lexicon` state, its remedy told by the 

1968 state's layout, since a caller holding an old pickle seldom knows 

1969 which release wrote it (decisions/vocabulary-model, 2026-11-08 

1970 #1003). It is raised wherever the `Lexicon` is, so a `Parser` or 

1971 locale pack holding one is named too. Any other layout is named by 

1972 the keys it lacks and holds beyond that one, as 3.0 named them.""" 

1973 held = "the Lexicon, or the Parser or locale pack holding it" 

1974 missing = sorted(_LAYOUT_3_0_LOADED - set(state)) 

1975 unexpected = sorted(set(state) - _LAYOUT_3_0_LOADED - {"given_names"}) 

1976 if not missing and not unexpected: 

1977 return ValueError( 

1978 f"this Lexicon was pickled by nameparser 2.7 or 2.8, which " 

1979 f"3.1 no longer loads: load the pickle under 3.0 and pickle " 

1980 f"the loaded object ({held}) again; if 3.0 refuses the " 

1981 f"pickle too, build the object again") 

1982 return ValueError( 

1983 f"this Lexicon was pickled by nameparser 2.x in a layout no 3.x " 

1984 f"release loads (missing: {', '.join(missing) or 'none'}; " 

1985 f"unexpected: {', '.join(unexpected) or 'none'}), as 2.6 and " 

1986 f"earlier wrote: build the object ({held}) again") 

1987 

1988 

1989# -- the public types ---------------------------------------------------- 

1990 

1991@dataclass(frozen=True, slots=True) 

1992class LexiconReading: 

1993 """One reading a :class:`Lexicon` holds for a word, as 

1994 :meth:`Lexicon.readings_of` returns it: what the word may be read 

1995 as, in the vocabulary files' terms (decisions/vocabulary-model, 

1996 2026-11-02 #754, item 2). 

1997 

1998 Whether the parse READ a word this way is the parse's 

1999 question, :attr:`Token.reading`: a title reading beside a ``given`` 

2000 one is a title only inside a title phrase (rules/H9). Added in 

2001 3.0.""" 

2002 

2003 #: The word, folded as the lexicon stores it (``dr``). 

2004 text: str 

2005 #: A vocabulary kind as the language files write it (``"office"``, 

2006 #: ``"credential"``, ``"preposition"``, ``"given"``), finer than 

2007 #: :class:`ReadingKind`, which is the parse's. 

2008 kind: str 

2009 #: The kind's category (``"title"``, ``"suffix"``, ``"particle"``, 

2010 #: ``"conjunction"``, ``"bound_given"``, ``"bound_second"``, 

2011 #: ``"relation"``, ``"name"``, ``"familiar"``, ``"spelling"``). 

2012 category: str 

2013 #: The behavioral properties as sorted ``(name, value)`` pairs, 

2014 #: spelled as the files spell them (``("addresses", "given")``), a 

2015 #: list value a sorted tuple. 

2016 properties: tuple[tuple[str, Any], ...] = () 

2017 #: The BCP 47 tags of the shipped files holding the reading, sorted; 

2018 #: empty for a reading a caller added. 

2019 languages: tuple[str, ...] = () 

2020 

2021 def __post_init__(self) -> None: 

2022 ri = _index_module() 

2023 for name in ("text", "kind", "category"): 

2024 if not isinstance(getattr(self, name), str): 

2025 raise TypeError(f"LexiconReading.{name} must be a string, " 

2026 f"got {getattr(self, name)!r}") 

2027 if self.kind not in ri.CATEGORY: 

2028 raise ValueError(f"unknown reading kind {self.kind!r}; the " 

2029 f"kinds are {', '.join(ri.CATEGORY)}") 

2030 if self.category != ri.CATEGORY[self.kind]: 

2031 raise ValueError( 

2032 f"{_a(self.kind)} {self.kind} reading's category is " 

2033 f"{ri.CATEGORY[self.kind]!r}, got {self.category!r}") 

2034 for name in ("properties", "languages"): 

2035 if not isinstance(getattr(self, name), tuple): 

2036 raise TypeError(f"LexiconReading.{name} must be a tuple, " 

2037 f"got {getattr(self, name)!r}") 

2038 

2039 def __getstate__(self) -> dict[str, object]: 

2040 return {f.name: getattr(self, f.name) 

2041 for f in dataclasses.fields(self)} 

2042 

2043 def __setstate__(self, state: dict[str, object]) -> None: 

2044 # the layout check the other frozen types share 

2045 # (_types._guarded_setstate), held here by layering 

2046 expected = {f.name for f in dataclasses.fields(LexiconReading)} 

2047 if set(state) != expected: 

2048 missing = ", ".join(sorted(expected - set(state))) or "none" 

2049 unexpected = ", ".join(sorted(set(state) - expected)) or "none" 

2050 raise ValueError( 

2051 f"incompatible LexiconReading pickle: missing fields: " 

2052 f"{missing}; unexpected fields: {unexpected}") 

2053 for name, value in state.items(): 

2054 object.__setattr__(self, name, value) 

2055 

2056 

2057@dataclass(frozen=True, slots=True, init=False, repr=False) 

2058class Lexicon: 

2059 """The vocabulary a parser matches against: which words may be read 

2060 as titles, particles, suffixes, and so on. Immutable and hashable. 

2061 Start from :meth:`default` (the shipped vocabulary) or 

2062 :meth:`empty`, configure it by READING -- :meth:`add` and 

2063 :meth:`remove` take words and a vocabulary kind as the language 

2064 files write it, ``add("leed", "ap", kind="credential")`` -- join 

2065 fragments with ``|``, and pass the result to ``Parser(lexicon=...)``. 

2066 Ask what a word may be read as with :meth:`readings_of`. 

2067 

2068 Words are normalized as they are stored -- lowercased, NFC-composed, 

2069 edge full stops stripped -- so matching is case-insensitive. 

2070 

2071 Since 3.0 the sets a parse reads are compiled from the readings and 

2072 are internal; the 2.x set fields (``titles``, ``suffix_acronyms``, 

2073 ...) are refused wherever they were written, each refusal naming 

2074 the field and pointing at docs/migrate.rst's table of the kind each 

2075 field's words take. Three fields stay, being outside the per-word model: 

2076 ``surnames``, ``given_names`` and ``capitalization_exceptions``. 

2077 

2078 State is a base (the shipped vocabulary, none, or a pickled 

2079 release's), the choice of languages :func:`~nameparser.parser_for` 

2080 records (:attr:`languages`, :attr:`strict`), the ordered log of 

2081 :meth:`add` and :meth:`remove` calls applied after the choice, and 

2082 the three fields; two lexicons are equal when all of them are, the log compared call by call as written, so two 

2083 logs that read alike can still differ (decisions/vocabulary-model, 

2084 2026-11-02 #754, item 3).""" 

2085 

2086 #: Family names for the unspaced-name segmentation stage (#271), 

2087 #: matched longest-first against the start of the FIRST token 

2088 #: written wholly in a script :attr:`Policy.segment_scripts 

2089 #: <nameparser.Policy.segment_scripts>` activates. The default 

2090 #: carries the Korean census list 

2091 #: (``nameparser/config/_ko_surnames.py``); Chinese 

2092 #: surnames ship in locales.ZH because Han segmentation is opt-in. 

2093 #: A list, outside the per-word model: add to it with a fragment, 

2094 #: ``lexicon | Lexicon(surnames={...})``. 

2095 surnames: frozenset[str] = frozenset() 

2096 #: Given names read by two-family-name handling alone 

2097 #: (:attr:`Policy.two_family_names 

2098 #: <nameparser.Policy.two_family_names>`, rules/O6): the word that 

2099 #: rule would take into the family stays where it is when listed, so 

2100 #: "José Luis Pérez" keeps family "Pérez". A word matches as 

2101 #: written or with its acute and grave accents and diaeresis 

2102 #: dropped (the tilde on n and the cedilla on c kept), so an entry 

2103 #: written "jose" matches "José" too. No other rule reads it. Empty 

2104 #: by default, so the switch reads as without it; a caller passes 

2105 #: a list of its own; ``locales.ES`` and ``locales.ES_AR`` carry 

2106 #: Spanish lists and ``locales.PT_BR`` and ``locales.PT_PT`` a 

2107 #: Portuguese one, each with the switch on. Added in 3.0. 

2108 given_names: frozenset[str] = frozenset() 

2109 #: Lowercase word -> case mask used by capitalized(): the word's 

2110 #: own letters and digits, each in the case it takes ("phd" -> 

2111 #: "PhD"), laid over the word as written, so the one entry 

2112 #: repairs "ph.d." to "Ph.D.". The mask's own punctuation marks 

2113 #: where its letters are joined into one run versus split apart, 

2114 #: and is never written into the word -- repair keeps the writer's 

2115 #: own punctuation. A value that does not spell the key's letters 

2116 #: and digits raises ValueError. Pair-valued: change it with 

2117 #: dataclasses.replace(); read it as a mapping via 

2118 #: capitalization_exceptions_map; the default's are 

2119 #: ``Lexicon.default().capitalization_exceptions``. 

2120 # Canonical storage: sorted tuple of (key, value) pairs. The 

2121 # constructor tolerates any Mapping (or pair iterable) at runtime and 

2122 # canonicalizes here; this closes the caller-aliasing hole and keeps 

2123 # Lexicon hashable. Read via capitalization_exceptions_map. 

2124 capitalization_exceptions: tuple[tuple[str, str], ...] = () 

2125 # The base, the log and the choice: constructor parameters under 

2126 # underscore names, so that dataclasses.replace and copy.replace 

2127 # carry them, and no public API (decisions/vocabulary-model, 

2128 # 2026-11-02 #754, item 3); a choice is set publicly by parser_for 

2129 # alone, and read through `languages` and `strict`. 

2130 _base: Any = "empty" 

2131 _edits: tuple[_Edit, ...] = () 

2132 # marked added: a 4i-b pickle, from no release, holds no choice and 

2133 # loads choosing nothing, its log already holding what a choice of 

2134 # 3b's delta had written into it 

2135 _languages: frozenset[str] = field( 

2136 default=frozenset(), metadata={_ADDED_IN: "3.0.0"}) 

2137 _strict: bool = field(default=False, metadata={_ADDED_IN: "3.0.0"}) 

2138 # the file tags the choice selects, derived from it 

2139 _chosen: frozenset[str] = field( 

2140 init=False, repr=False, compare=False, hash=False) 

2141 _cap_map: Mapping[str, str] = field( 

2142 init=False, repr=False, compare=False, hash=False) 

2143 _sets: _LexiconSets = field( 

2144 init=False, repr=False, compare=False, hash=False) 

2145 # group -> word -> the words it is a listed spelling of (`given`: 

2146 # `wm` -> {`william`}), from every reading's `same_as` in the group 

2147 # of its kind; built at construction, never pickled, like `_cap_map` 

2148 _same_as: SameAs = field( 

2149 init=False, repr=False, compare=False, hash=False) 

2150 # group -> the words with a link there that are a name of their own 

2151 # too (`jo` among given names), whose links need the period 

2152 # (`_headwords`); built like `_same_as` 

2153 _same_as_named: SameAsNamed = field( 

2154 init=False, repr=False, compare=False, hash=False) 

2155 # a given name -> every name it is paired with as a familiar form, 

2156 # either way (`max` -> {`maxwell`, `maximilian`, ...}, 

2157 # `maximilian` -> {`max`}), from every `familiar` reading's 

2158 # `short_for`, read by the name match alone (`_familiar_forms`); 

2159 # built like `_same_as` 

2160 _familiar: Familiar = field( 

2161 init=False, repr=False, compare=False, hash=False) 

2162 # a given name -> every name it is paired with as an alternate 

2163 # spelling, either way, from every `spelling` reading's 

2164 # `spelling_of`, read by the name match alone (`_alternate_spellings`); 

2165 # built like `_familiar` 

2166 _alternate: Familiar = field( 

2167 init=False, repr=False, compare=False, hash=False) 

2168 # what assemble keys Reading.languages by: one per base, log and 

2169 # choice (_ReadingFiles) 

2170 _files: _ReadingFiles = field( 

2171 init=False, repr=False, compare=False, hash=False) 

2172 

2173 def __init__( 

2174 self, *, 

2175 surnames: Iterable[str] = frozenset(), 

2176 given_names: Iterable[str] = frozenset(), 

2177 capitalization_exceptions: (Mapping[str, str] 

2178 | Iterable[tuple[str, str]]) = (), 

2179 _base: object = "empty", 

2180 _edits: Iterable[_Edit] = (), 

2181 _languages: Iterable[str] = frozenset(), 

2182 _strict: bool = False, 

2183 **removed: object, 

2184 ) -> None: 

2185 put = functools.partial(object.__setattr__, self) 

2186 put("surnames", _normset(surnames, "surnames")) 

2187 put("given_names", _normset(given_names, "given_names")) 

2188 canonical = _normpairs(capitalization_exceptions) 

2189 put("capitalization_exceptions", canonical) 

2190 put("_cap_map", MappingProxyType(dict(canonical))) 

2191 put("_base", _check_base(_base)) 

2192 if isinstance(_edits, (str, bytes)) or not isinstance( 

2193 _edits, Iterable): 

2194 raise TypeError(f"_edits must be a tuple of edits, got " 

2195 f"{_edits!r}") 

2196 edits = tuple(_edits) 

2197 for e in edits: 

2198 if not isinstance(e, tuple) or len(e) != 4: 

2199 raise TypeError(f"an edit is (op, words, kind, props), " 

2200 f"got {e!r}") 

2201 canon = tuple(_make_edit(*e) for e in edits) 

2202 if canon != edits: 

2203 raise ValueError( 

2204 "_edits holds an edit not in canonical form; build a " 

2205 "Lexicon's log with add() and remove()") 

2206 put("_edits", canon) 

2207 languages, chosen = _check_choice(_languages, _strict) 

2208 put("_languages", languages) 

2209 put("_strict", _strict) 

2210 put("_chosen", chosen) 

2211 compiled, same_as, named, familiar, alternate = _compiled_for( 

2212 self._base, canon, chosen, _strict) 

2213 put("_files", _reading_files(self._base, canon, chosen, _strict)) 

2214 put("_same_as", same_as) 

2215 put("_same_as_named", named) 

2216 put("_familiar", familiar) 

2217 put("_alternate", alternate) 

2218 put("_sets", _LexiconSets( 

2219 **compiled, surnames=self.surnames, given_names=self.given_names)) 

2220 if removed: 

2221 raise _refusal("Lexicon() (and dataclasses.replace)", removed) 

2222 

2223 # -- constructors ---------------------------------------------------- 

2224 

2225 @classmethod 

2226 def empty(cls) -> Lexicon: 

2227 """A lexicon holding no readings, no surnames, no given names 

2228 and no case masks, equal to ``Lexicon()``: the start for a 

2229 fragment to join onto another with ``|``, or for a vocabulary 

2230 built from nothing. A parser over it still reads by shape and 

2231 position (``Dr. John Smith`` keeps title ``Dr.``, a period-marked 

2232 word opening a name), and, the default :class:`Policy 

2233 <nameparser.Policy>` dividing unspaced Hangul, warns at 

2234 construction that no surnames cover it.""" 

2235 return cls() 

2236 

2237 @classmethod 

2238 def default(cls) -> Lexicon: 

2239 """The shipped vocabulary, the lexicon ``Parser()`` uses when 

2240 given none: every reading the language files turn on by 

2241 default, the Korean census surnames and the case masks, with no 

2242 :attr:`given_names` and no choice of languages. Cached, so 

2243 every call returns the same object, which being immutable is 

2244 safe to share; configure a copy with :meth:`add`, 

2245 :meth:`remove` or ``|``.""" 

2246 return _default_lexicon() 

2247 

2248 # -- dunders ---------------------------------------------------------- 

2249 

2250 # hidden from a type checker, which would otherwise read any 

2251 # attribute as defined and stop flagging `lexicon.titles` itself 

2252 if not TYPE_CHECKING: 

2253 def __getattr__(self, name: str) -> object: 

2254 if name in _SET_FIELDS: 

2255 raise AttributeError( 

2256 f"Lexicon.{name} is internal since 3.0, compiled from " 

2257 f"the lexicon's readings: ask lexicon.readings_of(word) " 

2258 f"what a word may be read as, and a parse's " 

2259 f"Token.reading what it was read as") 

2260 raise AttributeError( 

2261 f"{type(self).__name__!r} object has no attribute {name!r}") 

2262 

2263 def __repr__(self) -> str: 

2264 # Bounded: counts readings by kind against the nearer of the two 

2265 # named lexicons, never naming a word (the design rule in 

2266 # nameparser._types' module docstring) 

2267 # A choice is shown by its tags, and the readings counted against 

2268 # the named lexicon under the same choice 

2269 choice = "" 

2270 named = [("default", Lexicon.default()), ("empty", Lexicon.empty())] 

2271 if self._languages: 

2272 choice = ", " + _shown_choice(self._languages) + ( 

2273 ", strict" if self._strict else "") 

2274 named = [(label, dataclasses.replace( 

2275 other, _languages=self._languages, _strict=self._strict, 

2276 capitalization_exceptions=_rechosen_masks( 

2277 other, self._chosen, self._strict))) 

2278 for label, other in named] 

2279 for label, other in named: 

2280 if self == other: 

2281 return f"Lexicon({label}{choice})" 

2282 candidates = [(label, self._deltas_from(other)) 

2283 for label, other in named] 

2284 label, (kinds, lists) = min( 

2285 candidates, 

2286 key=lambda c: sum(a + r for _, a, r in c[1][0] + c[1][1])) 

2287 

2288 def counts(deltas: list[tuple[str, int, int]]) -> str: 

2289 return ", ".join( 

2290 name + ": " + "".join( 

2291 part for part, n in ((f"+{a}", a), (f"-{r}", r)) if n) 

2292 for name, a, r in deltas) 

2293 

2294 rendered = "; ".join(filter(None, (counts(kinds), counts(lists)))) 

2295 return (f"Lexicon({label} + {rendered or f'edits: {len(self._edits)}'}" 

2296 f"{choice})") 

2297 

2298 def __getstate__(self) -> dict[str, object]: 

2299 # the base as a snapshot of its rows, so a pickle parses as it 

2300 # did where it was written (decisions/vocabulary-model, 

2301 # 2026-11-02 #754, item 5) 

2302 base = self._base 

2303 if base == "default": 

2304 from nameparser.config._index import READINGS 

2305 base = READINGS 

2306 return {"surnames": self.surnames, "given_names": self.given_names, 

2307 "capitalization_exceptions": self.capitalization_exceptions, 

2308 "_base": base, "_edits": tuple(tuple(e) for e in self._edits), 

2309 "_languages": self._languages, "_strict": self._strict} 

2310 

2311 def __setstate__(self, state: dict[str, object]) -> None: 

2312 # A 2.x state holds the compiled sets, refused since 3.1 

2313 # (decisions/vocabulary-model, 2026-11-08 #1003); a 3.0 one is 

2314 # checked for its layout as _types._guarded_setstate checks the 

2315 # other frozen types', the one skew admitted a field marked 

2316 # `_ADDED_IN` with a default (`_languages`, `_strict`), and then 

2317 # built through the constructor, which validates every value as 

2318 # for a caller's. 

2319 if "titles" in state: 

2320 raise _refused_2x(state) 

2321 fields = [f for f in dataclasses.fields(Lexicon) if f.init] 

2322 expected = {f.name for f in fields} 

2323 added = {f.name: f.default for f in fields 

2324 if _ADDED_IN in f.metadata 

2325 and f.default is not dataclasses.MISSING} 

2326 missing_set = expected - set(state) - set(added) 

2327 if missing_set or not set(state) <= expected: 

2328 missing = ", ".join(sorted(missing_set)) or "none" 

2329 unexpected = ", ".join(sorted(set(state) - expected)) or "none" 

2330 raise ValueError( 

2331 f"incompatible Lexicon pickle: missing fields: {missing}; " 

2332 f"unexpected fields: {unexpected}") 

2333 defaulted = {name for name in added if name not in state} 

2334 state = {**{name: added[name] for name in defaulted}, **state} 

2335 Lexicon.__init__(self, **state) # type: ignore[misc, arg-type] 

2336 # The constructor normalizes, and quietly accepting a rewritten 

2337 # value would make this a place where caller data changes 

2338 # without a word. A pickle this library wrote is always 

2339 # normalized already (_normalize converges), so a difference 

2340 # here means the state came from somewhere else -- say so while 

2341 # the offending entries can still be named. 

2342 drifted = [] 

2343 for name in _LIST_FIELDS: 

2344 lost = frozenset( 

2345 cast("Iterable[str]", state[name])) - getattr(self, name) 

2346 if lost: 

2347 drifted.append(f"{name}: {', '.join(sorted(lost))}") 

2348 given_pairs = state["capitalization_exceptions"] 

2349 if (isinstance(given_pairs, tuple) 

2350 and given_pairs != self.capitalization_exceptions): 

2351 drifted.append("capitalization_exceptions") 

2352 faulty = [d for d in drifted if d.split(":")[0] in defaulted] 

2353 if faulty: 

2354 raise ValueError( 

2355 "Lexicon field default is not normalized " 

2356 f"({'; '.join(faulty)}): a field marked _ADDED_IN loads " 

2357 "its default into every pickle written before it, so " 

2358 "the default must be normalized entries; this is a " 

2359 "defect in nameparser, not in the pickle") 

2360 if drifted: 

2361 raise ValueError( 

2362 "incompatible Lexicon pickle: entries are not normalized " 

2363 f"({'; '.join(drifted)}); this state was not written by " 

2364 "this version of nameparser") 

2365 

2366 def __or__(self, other: Lexicon) -> Lexicon: 

2367 """The union of two lexicons: the lists unioned, the masks taken 

2368 right-biased, and the logs concatenated, this one's first, so a 

2369 later lexicon's edits apply after an earlier one's (decisions/ 

2370 vocabulary-model, 2026-11-02 #754, item 3); the base is the one 

2371 that is not empty and the choice the one that is made, and two 

2372 different bases, or two different choices, raise.""" 

2373 if not isinstance(other, Lexicon): 

2374 return NotImplemented 

2375 if (self._languages and other._languages 

2376 and (self._languages, self._strict) 

2377 != (other._languages, other._strict)): 

2378 raise ValueError( 

2379 "cannot join two lexicons compiled under different choices " 

2380 "of languages or of strictness; combine choices with " 

2381 "parser_for, which unions them: parser_for(*packs, " 

2382 "base=parser)") 

2383 mine = self if self._languages else other 

2384 if "empty" in (self._base, other._base) or self._base == other._base: 

2385 base = other._base if self._base == "empty" else self._base 

2386 else: 

2387 raise ValueError( 

2388 "cannot join two lexicons built on different bases (the " 

2389 "shipped vocabulary of two releases); rebuild one from " 

2390 "Lexicon.default() or Lexicon.empty()") 

2391 merged = dict(self._cap_map) | dict(other._cap_map) 

2392 return Lexicon( 

2393 surnames=self.surnames | other.surnames, 

2394 given_names=self.given_names | other.given_names, 

2395 capitalization_exceptions=tuple(sorted(merged.items())), 

2396 _base=base, _edits=self._edits + other._edits, 

2397 _languages=mine._languages, _strict=mine._strict) 

2398 

2399 # -- properties ------------------------------------------------------- 

2400 

2401 @property 

2402 def capitalization_exceptions_map(self) -> Mapping[str, str]: 

2403 return self._cap_map 

2404 

2405 @property 

2406 def languages(self) -> frozenset[str]: 

2407 """The languages this lexicon's readings are chosen under, as 

2408 BCP 47 tags; empty where none was chosen. Set by 

2409 :func:`~nameparser.parser_for`, which unions a base's choice 

2410 with its packs' (decisions/vocabulary-model, 2026-11-02 #754, 

2411 item 4): the shipped readings are filtered by the choice, and 

2412 the lexicon's own :meth:`add` and :meth:`remove` calls apply 

2413 after it. Added in 3.0.""" 

2414 return self._languages 

2415 

2416 @property 

2417 def strict(self) -> bool: 

2418 """Whether the choice is strict: only the chosen languages' 

2419 vocabulary files, mul.toml and native-script words' readings (as a 

2420 plain choice of the same languages keeps them) are read. Added in 3.0.""" 

2421 return self._strict 

2422 

2423 # -- access ----------------------------------------------------------- 

2424 

2425 def readings_of(self, word: str) -> tuple[LexiconReading, ...]: 

2426 """The readings this lexicon holds for `word`: one per kind and 

2427 properties, each with the shipped files that hold it, a reading 

2428 a caller added naming none; empty for a word it holds no reading 

2429 of. `word` is normalized as the lexicon stores it, a phrase 

2430 (``"z domu"``) whole. "Is X a title here?" is ``any(r.category 

2431 == "title" for r in lexicon.readings_of(x))``; whether a parse 

2432 read it as one is :attr:`Token.reading`'s. Added in 3.0.""" 

2433 _reject_buffer(word, "readings_of()", "characters") 

2434 if not isinstance(word, str): 

2435 raise TypeError(f"readings_of() takes a word, a string, got " 

2436 f"{word!r}") 

2437 text = _title_key(word.split()) 

2438 ri = _index_module() 

2439 grouped: dict[tuple[str, _Props], list[str]] = {} 

2440 for r in self._pool().get(text, ()): 

2441 if r.on_by_default: 

2442 grouped.setdefault((r.kind, _clean(r.props)), []).append( 

2443 r.tag) 

2444 order = list(ri.CATEGORY) 

2445 return tuple( 

2446 LexiconReading(text, kind, ri.CATEGORY[kind], props, 

2447 tuple(sorted(t for t in set(tags) if t))) 

2448 for (kind, props), tags in sorted( 

2449 grouped.items(), 

2450 key=lambda item: (order.index(item[0][0]), repr(item[0][1])))) 

2451 

2452 def words(self, *, kind: str, **properties: object) -> tuple[str, ...]: 

2453 """The words holding a reading of `kind` on in this lexicon, 

2454 sorted: a kind or a category, as :meth:`remove` takes it 

2455 (``words(kind="title")`` lists every title word, ``dean`` 

2456 among them, whichever set its readings compile to), and 

2457 `properties`, which a kind takes (``title``, ``suffix`` and 

2458 ``particle`` are kinds as well as categories, and take their 

2459 own kind's properties), narrowing to the readings that carry 

2460 them as :meth:`add` spells them, each compared in its own 

2461 reading's kind (so through a category an unwritten value means 

2462 each kind's own: ``acronym=None`` under ``suffix`` lists the 

2463 credentials, unwritten-true, and the suffix words, unwritten- 

2464 false, alike) 

2465 (``words(kind="title", addresses="given")``, the titles that 

2466 address a person by the given name). ``same_as`` matches a 

2467 reading naming every word given among the words it is a 

2468 spelling of (``words(kind="given", same_as="muhammad")`` lists 

2469 ``md``, ``mohd`` and ``moh`` among others). A 

2470 phrase the lexicon holds whole (``"z domu"``) is one entry. 

2471 Added in 3.0.""" 

2472 k = _check_kind(kind, "words") 

2473 assert k is not None 

2474 ri = _index_module() 

2475 if properties: 

2476 if k not in ri.CATEGORY: 

2477 raise ValueError( 

2478 f"words() takes properties with a kind, not the " 

2479 f"category {k!r}; name one of its kinds: " + ", ".join( 

2480 x for x, c in ri.CATEGORY.items() if c == k)) 

2481 # checked against the kind named; compared below against 

2482 # each reading's own kind, since a kind that is also a 

2483 # category reaches kinds whose unwritten value differs 

2484 # (`acronym` is unwritten-true on a credential, false on a 

2485 # suffix word) 

2486 _edit_props(k, properties) 

2487 

2488 return tuple(sorted( 

2489 w for w, rs in self._pool().items() 

2490 if any(r.on_by_default and (r.kind == k or r.category == k) 

2491 # a reading holds its properties canonical, as the 

2492 # build and add write them, the unwritten value never 

2493 and all(_carries(r.props, p, _prop_value(r.kind, p, v)) 

2494 for p, v in properties.items()) 

2495 for r in rs))) 

2496 

2497 # -- editing ---------------------------------------------------------- 

2498 

2499 # `kind` is required, and a type checker reads it so: the runtime 

2500 # default exists only to catch a 2.x call, which names no kind, and 

2501 # refuse it pointing at docs/migrate.rst's table of kinds rather than 

2502 # with Python's own missing-argument error 

2503 if TYPE_CHECKING: 

2504 def add(self, *words: str, kind: str, 

2505 **properties: object) -> Lexicon: ... 

2506 else: 

2507 def add(self, *words: str, kind: str | None = None, 

2508 **properties: object) -> Lexicon: 

2509 """This lexicon with a reading of `kind` added to each word. 

2510 `kind` is required; the signature's default exists only so 

2511 that a 2.x call, which names no kind, is refused pointing at 

2512 docs/migrate.rst's table of kinds. It is a vocabulary kind as 

2513 the language files write it, a key of 

2514 ``nameparser._reading_index.CATEGORY`` (``"title"``, 

2515 ``"office"``, ``"credential"``, ``"generation"``, 

2516 ``"preposition"``, ``"conjunction"``, ``"bound_given"``, 

2517 ``"bound_second"`` (3.2), ``"birth_marker"``, ``"alias_marker"`` 

2518 (3.2), ``"given"``, 

2519 ``"family"``, ...), and 

2520 `properties` that kind's behavioral properties as the files 

2521 spell them (``addresses="given"``, ``after_given=True``, 

2522 ``abbreviation=True``, ``attaches=[...]``, ``acronym=...``, ``attached="after"`` on a suffix word reading 

2523 and ``attached="before"`` on a one-word title reading (rules/W2 

2524 and W6), 

2525 ``may_be_initial=True``, ``completed_by=[...]``, 

2526 ``completes_any=True`` and ``long_names_only=True`` on a 

2527 ``bound_given`` reading, ``completes=[...]`` on a 

2528 ``bound_second`` reading, ``after_particle=True`` on a 

2529 ``given`` reading, ``shared=True`` on a name reading, 

2530 ``capital_opening=True`` on a particle reading, 

2531 ``dotted=True`` on a title reading, and 

2532 ``same_as=...`` on a reading of any kind: the word this one 

2533 is a spelling of, or a list of them where it is a spelling 

2534 of several (``same_as=["muhammad", "mohammad"]``), which name 

2535 matching reads as a 

2536 ``listed-spelling`` and keys alike in the roles that read 

2537 the kind's words (a ``given`` reading's in the given name, 

2538 middle name and nickname, a ``family`` reading's in the 

2539 family and maiden names, a title's and a suffix's in theirs), 

2540 and which on a ``given`` reading also marks a given name 

2541 written short; written on a word, it applies to the word's 

2542 given readings, so the word keeps no plain given reading 

2543 and its link counts written bare, where a word the 

2544 vocabulary also holds as a name of its own counts only 

2545 written with its period. ``short_for=[...]`` on a 

2546 ``familiar`` reading names the longer given names a familiar 

2547 form stands for, which name matching reads as a 

2548 ``familiar-form`` where that outcome is accepted and no 

2549 parse reads (``add("max", kind="familiar", 

2550 short_for=["maxwell"])``); it EXTENDS the longer names 

2551 the word's shipped familiar readings list, in a reading of 

2552 the caller's own that names no file, rather than replacing 

2553 them (unlike an add of any other kind the word holds); to 

2554 replace them, ``remove(word, kind="familiar")`` first, and 

2555 to cut one pair, ``Max`` / ``Maximilian``, name it: 

2556 ``remove("max", kind="familiar", 

2557 short_for=["maximilian"])``, either name first. 

2558 ``spelling_of=[...]`` on a ``spelling`` reading is its twin: 

2559 the given names the word is another spelling of, by the 

2560 person's or a romanization's choice, which name matching 

2561 reads as an ``alternate-spelling`` where that outcome is 

2562 accepted and no parse reads (``add("olha", 

2563 kind="spelling", spelling_of=["olga"])``), extending as a 

2564 familiar reading does. A property 

2565 given its unwritten value (``None``, ``False``) is removed. Where the word holds a reading of `kind` 

2566 already, the add updates its properties in every file holding 

2567 it; otherwise it adds the caller's own reading, which names no 

2568 file. Warns where it makes a title reading that a ``given`` 

2569 reading keeps a title only inside a title phrase (rules/H9), 

2570 naming the ``remove`` that makes it a title everywhere.""" 

2571 _refuse_2x("add()", properties) 

2572 if kind is None: 

2573 raise TypeError("add() missing required keyword argument " 

2574 "'kind', e.g. add('leed', kind='credential')") 

2575 edit = _make_edit("add", words, kind, properties) 

2576 added = dataclasses.replace(self, _edits=self._edits + (edit,)) 

2577 ri = _index_module() 

2578 if ri.CATEGORY[edit.kind] == "title": # type: ignore[index] 

2579 before = self._pool() 

2580 for w in edit.words: 

2581 if (w in added._sets.titles_ambiguous 

2582 and not _updates(before.get(w, ()), edit)): 

2583 _warn_at_caller( 

2584 f"{w!r} holds a given reading, so it reads as a " 

2585 f"title only inside a title phrase (rules/H9) and " 

2586 f"this add reads no name differently elsewhere; to " 

2587 f"read it as a title everywhere, write " 

2588 f".remove({w!r}, kind='given')") 

2589 return added 

2590 

2591 def remove(self, *words: str, kind: str | None = None, 

2592 every: bool = False, **pairs: object) -> Lexicon: 

2593 """This lexicon without each word's readings of `kind`: a kind, 

2594 or a category, matching every kind of it (``kind="title"`` takes 

2595 out ``dean``'s ``office`` reading, ``kind="name"`` its ``given`` 

2596 and ``family`` ones), or None, taking out every reading, so the 

2597 word leaves the vocabulary. With ``every=True``, no words and a 

2598 `kind`, every word's readings of it go (``remove(kind="title", 

2599 every=True)``), those a later choice of languages turns on 

2600 included; a call with no words and no `every` raises, so an 

2601 empty ``remove(*words, kind=...)`` never takes out a whole kind. 

2602 Removing a reading the word does not hold changes nothing now, 

2603 and is kept: a later choice of languages may turn that reading 

2604 on. Where no vocabulary file holds the reading, on by default or 

2605 not, and no :meth:`add` earlier in this lexicon's log (a joined 

2606 lexicon's included) gave it, the edit can never take effect, and 

2607 the call warns with a ``UserWarning`` (#1535); a remove of every 

2608 word's readings and a ``familiar`` or ``spelling`` pair remove 

2609 are not judged. The message opens with the call and "changes 

2610 nothing", and says which case it is: a word holding other kinds 

2611 (they are listed, and the call to paste offered where one is 

2612 plainly meant, never a pair kind); a word held only in the 

2613 ``surnames`` or ``given_names`` list, which ``remove`` does not 

2614 edit (the ``dataclasses.replace`` that drops it); a word held 

2615 only as the other name of other words' ``familiar`` or 

2616 ``spelling`` pairs (the pair remove that reaches them); or a 

2617 word in no file and no earlier add. A fragment meant to remove a word 

2618 another lexicon adds warns, since ``remove`` cannot see the 

2619 lexicon it will be joined with: filter that warning by its 

2620 message, or do the remove on the joined lexicon. 

2621 

2622 A ``familiar`` or ``spelling`` reading is a pair of given names, 

2623 stored on one of the two and read by name matching both ways, so 

2624 removing one reaches both names. ``remove("robert", 

2625 kind="familiar")`` drops every pair naming ``robert``: the 

2626 word's own familiar readings and its name in every other 

2627 word's (``bob``, ``rob``, ...), whose other pairs stay. 

2628 ``remove("alex", kind="familiar", short_for=["alexis"])`` drops 

2629 that one pair, whichever name is written first and whichever 

2630 holds it, and ``remove("sarah", kind="spelling", 

2631 spelling_of=["sara"])`` an alternate spelling's; several words 

2632 and several names drop every pair of one with the other. A 

2633 name is compared as matching reads it, case and accents folded 

2634 and a letter a keyboard lacks written out or not, so a pair the 

2635 files store accented (``álex``) goes with the word written 

2636 plain; a pair two names reach only through a listed spelling 

2637 of one (``Wm`` / ``Bill``, through ``william``) is removed by 

2638 the name that stores it. With no `kind`, a remove takes the 

2639 word's own readings and not the pairs other words hold with 

2640 it, which are those words' readings. Many removes are cheapest 

2641 in one call, ``remove(*words, kind=...)``: every call replays 

2642 the log. A pair goes from every file that lists it, under any choice of 

2643 languages; edits apply in the order written, so a pair added 

2644 after the remove stands. No other kind takes a property here: 

2645 to take a property off a reading, :meth:`add` it with its 

2646 unwritten value.""" 

2647 _refuse_2x("remove()", pairs) 

2648 _refuse_unpaired(pairs) 

2649 if not isinstance(every, bool): 

2650 raise TypeError(f"remove() takes every as True or False, got " 

2651 f"{every!r}") 

2652 if every and words: 

2653 raise TypeError( 

2654 f"remove() takes words or every=True, not both: every=True " 

2655 f"takes out every word's readings of the kind; got " 

2656 f"{len(words)} word(s)") 

2657 if every and kind is None: 

2658 raise TypeError( 

2659 "remove(every=True) takes a kind, e.g. remove(kind='title', " 

2660 "every=True); to remove everything, start from " 

2661 "Lexicon.empty()") 

2662 if not every and not words: 

2663 raise TypeError( 

2664 "remove() takes at least one word, e.g. remove('dean', " 

2665 "kind='title'), or every=True with a kind to take out every " 

2666 "word's readings of it, e.g. remove(kind='title', " 

2667 "every=True)") 

2668 edit = _make_edit("remove", words, kind, pairs) 

2669 for message in self._inert_removes(edit): 

2670 _warn_at_caller(message) 

2671 return dataclasses.replace(self, _edits=self._edits + (edit,)) 

2672 

2673 # -- private helpers -------------------------------------------------- 

2674 

2675 def _inert_removes(self, edit: _Edit) -> list[str]: 

2676 """A warning for each word of a `remove` that no vocabulary file 

2677 and no `add` earlier in this lexicon's log (a joined lexicon's 

2678 included) gives a reading of the kind asked (any reading, with 

2679 no kind), so that the edit can take effect under no choice of 

2680 languages (#1535). A file's reading counts whether it is on by 

2681 default or not, since a choice may turn it on. Read at `remove` 

2682 alone, never when a constructor replays the log or a pickle 

2683 loads. A remove of every word's readings (no words) and the 

2684 familiar and spelling pair removes, which match names by their 

2685 folded forms, are not judged. Each message opens with the call 

2686 and "changes nothing", so a caller filters one by it.""" 

2687 ri = _index_module() 

2688 kind = edit.kind 

2689 if not edit.words or (kind is not None and ri.CATEGORY.get( 

2690 kind, kind) in ri.MATCHING_ONLY): 

2691 return [] 

2692 added: dict[str, set[str]] = {} 

2693 for earlier in self._edits: 

2694 if earlier.op == "add" and earlier.kind is not None: 

2695 for w in earlier.words: 

2696 added.setdefault(w, set()).add(earlier.kind) 

2697 messages = [] 

2698 for w in dict.fromkeys(edit.words): 

2699 held = {r.kind for r in ri.readings_of(w)} | added.get(w, set()) 

2700 if kind is None and held: 

2701 continue 

2702 if kind is not None and any( 

2703 k == kind or ri.CATEGORY[k] == kind for k in held): 

2704 continue 

2705 call = (f"remove({w!r})" if kind is None 

2706 else f"remove({w!r}, kind={kind!r})") 

2707 head = f"{call} changes nothing: " 

2708 if held: 

2709 messages.append(head + self._other_kinds(w, kind, held)) 

2710 else: 

2711 messages.append(head + self._no_reading(w, kind, added)) 

2712 return messages 

2713 

2714 def _other_kinds(self, w: str, kind: str | None, 

2715 held: set[str]) -> str: 

2716 """Case (i) of #1535: the word holds readings, none of `kind`. 

2717 The call to paste is offered only where one kind is plainly the 

2718 one meant: the single held kind of the asked kind's category, 

2719 else the single held kind of all; a familiar or spelling kind is 

2720 never offered, its remove reaching name matching's pairs.""" 

2721 ri = _index_module() 

2722 kinds = sorted(held) 

2723 candidates = [k for k in kinds if ri.CATEGORY[k] not in 

2724 ri.MATCHING_ONLY] 

2725 same = [k for k in candidates 

2726 if ri.CATEGORY[k] == ri.CATEGORY.get(kind or "", kind)] 

2727 offer = (same[0] if len(same) == 1 else 

2728 candidates[0] if not same and len(candidates) == 1 else None) 

2729 text = (f"{w!r} has no {kind!r} reading in any vocabulary file or " 

2730 f"earlier add(); it holds: {', '.join(kinds)}") 

2731 if offer is not None: 

2732 text += f". Did you mean remove({w!r}, kind={offer!r})?" 

2733 return text 

2734 

2735 def _no_reading(self, w: str, kind: str | None, 

2736 added: dict[str, set[str]]) -> str: 

2737 """Cases (ii) and (iii) of #1535: the word holds no reading. It 

2738 may stand in the two lists, which remove() does not edit, be 

2739 only the other name of other words' familiar or spelling pairs, 

2740 which a remove of the pair kind takes, or be a suffix acronym or 

2741 a dotted title written with its full stops (``ph.d``, held as 

2742 ``phd``), where the bare word holds the kind asked; else it is 

2743 in no file.""" 

2744 ri = _index_module() 

2745 lists = {"surnames": ("family", "name"), "given_names": ("given", "name")} 

2746 for list_field, kinds in lists.items(): 

2747 if w in getattr(self, list_field) and ( 

2748 kind is None or kind in kinds): 

2749 return (f"{w!r} holds no reading, only an entry in this " 

2750 f"lexicon's {list_field} list, which remove() does " 

2751 f"not edit; drop it with dataclasses.replace(" 

2752 f"lexicon, {list_field}=lexicon.{list_field} - " 

2753 f"{{{w!r}}})") 

2754 pair_kind = ("familiar" if self._familiar_forms(w) 

2755 or w in _pair_names("familiar") else 

2756 "spelling" if self._alternate_spellings(w) 

2757 or w in _pair_names("spelling") else None) 

2758 if pair_kind is not None: 

2759 return (f"{w!r} holds no reading of its own, only the other " 

2760 f"name of {pair_kind} pairs other words hold; " 

2761 f"remove({w!r}, kind={pair_kind!r}) takes those pairs") 

2762 # only where the parse reads the dotted spelling as the bare word: 

2763 # a suffix acronym (M.D. as md) or a dotted title (U.S. as us), 

2764 # and the bare word holds the kind asked 

2765 bare = w.replace(".", "") 

2766 bare_kinds = ({r.kind for r in ri.readings_of(bare)} 

2767 | added.get(bare, set())) 

2768 # the kind the dotted spelling is read by: a suffix acronym's 

2769 # suffix reading, a dotted title's title one (M.D. is md's 

2770 # credential, not its given reading, Muhammad written short) 

2771 read_as = {k for k in bare_kinds if ri.CATEGORY[k] == ( 

2772 "suffix" if bare in self._sets.suffix_acronyms else "title")} 

2773 if bare != w and bare in (self._sets.suffix_acronyms 

2774 | self._sets.dotted_titles): 

2775 text = (f"the vocabulary writes {w!r} without its full stops, " 

2776 f"as {bare!r}") 

2777 asked = [k for k in read_as if kind is not None 

2778 and (k == kind or ri.CATEGORY[k] == kind)] 

2779 if kind is None and len(read_as) == 1: 

2780 offer: str | None = next(iter(read_as)) 

2781 elif len(asked) == 1: 

2782 offer = kind 

2783 else: 

2784 offer = None 

2785 if offer is not None: 

2786 return text + (f": did you mean remove({bare!r}, " 

2787 f"kind={offer!r})?") 

2788 return text + (", read with its full stops as " 

2789 + ", ".join(sorted(read_as))) 

2790 return (f"{w!r} is in no vocabulary file and no earlier add() of " 

2791 f"this lexicon; check its spelling, or, where a lexicon " 

2792 f"this one is joined with adds it, remove it from the " 

2793 f"joined lexicon") 

2794 

2795 def _pool(self) -> Pool: 

2796 return self._files.pool() 

2797 

2798 def _headwords(self, word: str, group: str, *, 

2799 period: bool = True) -> frozenset[str]: 

2800 """Every word reachable from `word`, normalized, through the 

2801 `same_as` links of `group` (`given`, `family`, `title` or 

2802 `suffix`, the group of the readings' kinds), the word itself 

2803 included: `Wm.` among given names is {`wm`, `william`}, and `sr` 

2804 among titles {`sr`, `señor`, `senhor`}. A word's readings of 

2805 another kind are another group's (`ma` is María written short 

2806 among given names and only itself among surnames), and a word 

2807 with no listed spelling is itself alone. A loop, which a 

2808 caller's edits can write where the build refuses it in the 

2809 files, yields every word in it. The name match reads two words 

2810 as listed spellings of each other where their sets meet. `period` 

2811 says whether the word was written with its trailing full stop, 

2812 which normalizing drops: a word that is a name of its own in 

2813 `group` as well as a spelling (`jo`, José written short and the 

2814 given name Jo) reaches its links only where it was, and is itself 

2815 alone where it was not.""" 

2816 links = self._same_as.get(group) 

2817 if links is None: 

2818 raise ValueError(f"unknown same_as group {group!r}; the groups " 

2819 f"are {', '.join(sorted(_SAME_AS_GROUPS))}") 

2820 start = _normalize(word) 

2821 if not period and start in self._same_as_named[group]: 

2822 return frozenset({start}) 

2823 seen = {start} 

2824 todo = [start] 

2825 while todo: 

2826 for head in links.get(todo.pop(), ()): 

2827 if head not in seen: 

2828 seen.add(head) 

2829 todo.append(head) 

2830 return frozenset(seen) 

2831 

2832 def _familiar_forms(self, word: str) -> frozenset[str]: 

2833 """The given names `word`, normalized, is paired with directly 

2834 as a familiar form, in either direction (`max` -> {`maxwell`, 

2835 `maximilian`, ...}, `maximilian` -> {`max`}), empty for a 

2836 word in no pair. Never chained: two longer names paired with 

2837 one shorter one (`maximilian`, `maxim`) do not reach each 

2838 other. Read by the name match alone, never by a parse.""" 

2839 return self._familiar.get(_normalize(word), frozenset()) 

2840 

2841 def _alternate_spellings(self, word: str) -> frozenset[str]: 

2842 """The given names `word`, normalized, is paired with directly 

2843 as an alternate spelling, in either direction (`olha` -> 

2844 {`olga`}, `olga` -> {`olha`}), empty for a word in no pair. 

2845 Never chained, as familiar forms are not: `aleksej` and `aleksey`, 

2846 each paired with `aleksei`, do not reach each other. Read by the 

2847 name match alone, never by a parse.""" 

2848 return self._alternate.get(_normalize(word), frozenset()) 

2849 

2850 def _deltas_from(self, other: Lexicon) -> tuple[ 

2851 list[tuple[str, int, int]], list[tuple[str, int, int]]]: 

2852 ri = _index_module() 

2853 mine, theirs = _keyed(self._pool()), _keyed(other._pool()) 

2854 added = Counter(key[1] for key in mine - theirs) 

2855 gone = Counter(key[1] for key in theirs - mine) 

2856 kinds = [(kind, added[kind], gone[kind]) for kind in ri.CATEGORY 

2857 if added[kind] or gone[kind]] 

2858 lists = [] 

2859 for name in _LIST_FIELDS + ("capitalization_exceptions",): 

2860 m, t = set(getattr(self, name)), set(getattr(other, name)) 

2861 if m != t: 

2862 lists.append((name, len(m - t), len(t - m))) 

2863 return kinds, lists 

2864 

2865 

2866def _keyed(pool: Pool) -> set[tuple[str, str, _Props]]: 

2867 """The readings on in `pool`, each once, as the repr counts them: 

2868 by word, kind and properties, whatever file holds them.""" 

2869 return {(r.text, r.kind, _clean(r.props)) 

2870 for rs in pool.values() for r in rs if r.on_by_default} 

2871 

2872 

2873def _updates(held: Iterable[Any], edit: _Edit) -> bool: 

2874 """Whether `edit` only updates the properties of a reading of its 

2875 kind the word holds: the title warning's exemption (decisions/ 

2876 vocabulary-model, 2026-11-01 #754, the title warning).""" 

2877 return any(r.kind == edit.kind 

2878 and _clean(_merged(r.props, edit.props)) != _clean(r.props) 

2879 for r in held) 

2880 

2881 

2882@functools.cache 

2883def _default_lexicon() -> Lexicon: 

2884 # nameparser/config/_compiled.py, compiled from nameparser/vocab/, is 

2885 # the single source of the default vocabulary: its sets are read from 

2886 # it, never compiled from the index here (_compiled_for), so 

2887 # Lexicon.default() loads no index. 

2888 from nameparser.config._compiled import CAPITALIZATION_EXCEPTIONS 

2889 from nameparser.config._ko_surnames import KOREAN_SURNAMES 

2890 

2891 # every vocabulary constant is a frozenset since #293, and this 

2892 # cache reading them ONCE is the reason they are frozen. 

2893 return Lexicon( 

2894 surnames=KOREAN_SURNAMES, 

2895 # pass canonical pair-tuples so this strictly-typed call site never 

2896 # feeds a Mapping to the tuple-annotated field; __init__ still 

2897 # tolerates a Mapping at runtime for interactive use 

2898 capitalization_exceptions=tuple(sorted(CAPITALIZATION_EXCEPTIONS.items())), 

2899 _base="default", 

2900 )