Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_match.py: 30%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""Name matching: the settings object, the result types and the check.
3Not a stage: nothing here runs inside a parse. `Matching` carries a
4`Parser`, the set of outcomes the caller accepts and the switch for
5other readings, and its `check` compares two parsed names role by
6role.
7Produces: `Outcome`, `Side`, `RoleMatch`, `CrossRoleMatch`, `MatchResult`,
8`DEFAULT_ACCEPT` and `Matching`.
9Reads: the `Parser`'s `Lexicon`, for the listed spellings (`same_as`)
10through `Lexicon._headwords`, each role in the group of its kind
11(its `_RULES` row), for the familiar forms (`short_for`) through
12`Lexicon._familiar_forms`, for the alternate spellings
13(`spelling_of`) through `Lexicon._alternate_spellings`, and for `Lexicon.particles`, a hyphen half
14that is a listed particle being set aside, and its `revise`, for a
15name's other readings (`Matching.other_readings`); no `Policy` field.
17Consistent means nothing in the two names contradicts it, under the
18outcomes the caller accepts. The module imports `_types`, `_policy`
19(for `Policy()`, which the repr compares a parser's policy with) and
20`_lexicon` (for
21`_normalize`, which folds a hyphen half before it is looked up among
22the particles, `Lexicon.default()`, which the repr compares a
23parser's lexicon with, `_fold` and `_forms`, the fold and the folded
24forms the match compares and keys a word by, and `FULL_STOPS`, the
25full stops a word written short ends in), `_pipeline._vocab` (for `_HYPHEN_CHARS`, the
26hyphens the pipeline joins two names with, every one of which the
27match reads as the hyphen-minus, `_HYPHENS`, the pattern a word
28is cut at them by, and `in_initialless_script`, the scripts that
29write no initials), `_parser` at call time, in the constructor and
30the repr, to tell a `Parser` from anything else, and `Parser` for
31typing too.
32"""
33from __future__ import annotations
35import dataclasses
36import functools
37import re
38import unicodedata
39from collections.abc import Callable, Iterable, Iterator, Mapping
40from dataclasses import dataclass
41from enum import StrEnum
42from typing import TYPE_CHECKING
44from nameparser._lexicon import FULL_STOPS, Lexicon, _normalize
45from nameparser._lexicon import _fold as _lexicon_fold
46from nameparser._lexicon import _forms as _lexicon_forms
47from nameparser._pipeline._vocab import (
48 _HYPHEN_CHARS,
49 _HYPHENS,
50 in_initialless_script,
51)
52from nameparser._policy import Policy
53from nameparser._types import (
54 UNJOINED_TAG,
55 Ambiguity,
56 ParsedName,
57 Role,
58 _coerce_enum,
59 _guarded_getstate,
60 _guarded_setstate,
61)
63if TYPE_CHECKING:
64 from nameparser._parser import Parser
67class Outcome(StrEnum):
68 """How one role of one name compares with the same role of another,
69 listed in the order `check` ranks them, strongest first. `strength`
70 is that rank as an ordinal, larger for a stronger outcome and 0 for
71 `conflict`; compare outcomes by it, since `<` on an Outcome
72 compares the names as strings (`folded` sorts before `same`), but
73 never store one: the values change when an outcome is added.
74 `conflict` is the one outcome that is never accepted. The search
75 for each side's other readings is not an outcome but a switch,
76 `Matching.other_readings`, and the reading used is named in
77 `MatchResult.left_alternative` and `right_alternative`."""
79 #: The two texts are equal as written.
80 SAME = "same"
81 #: Equal once case, accents, full stops and apostrophes are folded
82 #: away, each joining hyphen is read as the hyphen-minus, and a
83 #: letter a keyboard lacks is read as typed.
84 FOLDED = "folded"
85 #: Equal once folded and stripped of spaces and hyphens, save where
86 #: both are initials alone (``LaRussa`` / ``La Russa``).
87 JOINED = "joined"
88 #: Spellings the vocabulary lists as one (``Wm.`` / ``William``).
89 LISTED_SPELLING = "listed-spelling"
90 #: The family names, or the maiden names, agree without their
91 #: particles (``de la Vega`` / ``Vega``).
92 PARTICLES_ASIDE = "particles-aside"
93 #: One family or maiden name's words are among the other's, or
94 #: listed spellings of them, save where both are initials alone.
95 PART_OF_OTHER = "part-of-other"
96 #: An initial against a name, outside the family name, and a given
97 #: name of capitals against the names that spell it (``JP`` /
98 #: ``John Paul``).
99 INITIAL = "initial"
100 #: One role written in initials alone on both sides, the same
101 #: initials in the same order.
102 INITIALS_AGREE = "initials-agree"
103 #: A middle name, nickname or maiden name on one side only.
104 ONE_SIDE = "one-side"
105 #: A generation on one side only.
106 GENERATION_ONE_SIDE = "generation-one-side"
107 #: Titles and credentials, which never conflict.
108 NOTED = "noted"
109 #: Two given names the vocabulary lists as one name spelled two
110 #: ways (``Yuliya`` / ``Iuliia``). Not accepted by default.
111 ALTERNATE_SPELLING = "alternate-spelling"
112 #: Two given names the vocabulary lists as a familiar-form pair
113 #: (``Bill`` / ``William``). Not accepted by default.
114 FAMILIAR_FORM = "familiar-form"
115 #: The family name written as an initial. Not accepted by default.
116 FAMILY_INITIAL = "family-initial"
117 #: A given name on one side only. Not accepted by default.
118 GIVEN_ONE_SIDE = "given-one-side"
119 #: A given name against the first half of a hyphenated one
120 #: (``Hong`` / ``Hong-Yi``). Not accepted by default.
121 HYPHENATED_PART = "hyphenated-part"
122 #: A name in a different role on each side, recorded in
123 #: :attr:`MatchResult.across`. Not accepted by default.
124 ACROSS_ROLES = "across-roles"
125 #: The two texts contradict each other; never accepted.
126 CONFLICT = "conflict"
128 @property
129 def strength(self) -> int:
130 """The outcome's rank as an ordinal to compare outcomes by:
131 `conflict` is 0, and each outcome declared before another is
132 stronger than it, `same` the strongest. The values change when
133 an outcome is added, so compare them, never store one."""
134 return _STRENGTH[self]
137#: Each outcome's strength, from its declaration order.
138_STRENGTH: Mapping[Outcome, int] = {
139 o: len(Outcome) - 1 - i for i, o in enumerate(Outcome)}
142class Side(StrEnum):
143 """Which side of a comparison carried more of the role's text."""
145 #: The left name carried more of the role's text.
146 LEFT = "left"
147 #: The right name carried more of the role's text.
148 RIGHT = "right"
149 #: Neither name carried more than the other.
150 NEITHER = "neither"
153_MIRROR = {Side.LEFT: Side.RIGHT, Side.RIGHT: Side.LEFT, Side.NEITHER: Side.NEITHER}
156@dataclass(frozen=True, slots=True)
157class RoleMatch:
158 """One role's comparison: the outcome, both sides' text, and which
159 side carried more. On a row read `across-roles`, the side carrying
160 more is the one whose name held both the role and the cross role
161 the match used (`J. Edgar Hoover` / `Edgar Hoover`: left)."""
163 #: The role compared.
164 role: Role
165 #: How the two sides' text of the role compares.
166 outcome: Outcome
167 #: The left name's text of the role.
168 left: str
169 #: The right name's text of the role.
170 right: str
171 #: Which side carried more of the role's text.
172 more: Side
174 __getstate__ = _guarded_getstate
175 __setstate__ = _guarded_setstate
177 def mirrored(self) -> RoleMatch:
178 """The same comparison with the two names swapped."""
179 return RoleMatch(self.role, self.outcome, self.right, self.left,
180 _MIRROR[self.more])
183@dataclass(frozen=True, slots=True)
184class CrossRoleMatch:
185 """A role of one name matched against a different role of the
186 other (`across-roles`): the left name's role and text, the right
187 name's role and text, and the outcome of comparing the two texts."""
189 #: The left name's role the match used.
190 left_role: Role
191 #: The right name's role the match used.
192 right_role: Role
193 #: The outcome of comparing the two texts.
194 outcome: Outcome
195 #: The left name's text in ``left_role``.
196 left: str
197 #: The right name's text in ``right_role``.
198 right: str
200 __getstate__ = _guarded_getstate
201 __setstate__ = _guarded_setstate
203 def mirrored(self) -> CrossRoleMatch:
204 """The same match with the two names swapped."""
205 return CrossRoleMatch(self.right_role, self.left_role, self.outcome,
206 self.right, self.left)
209#: The code a refused `bool(result)` is offered; it runs and type-checks.
210_CONSISTENT_HINT = ('e.g. parser.matching().check("John Smith", "J. Smith")'
211 '.consistent')
214@dataclass(frozen=True, slots=True)
215class MatchResult:
216 """The result of comparing two names: whether nothing in them
217 contradicts the match under the accepted outcomes, one `RoleMatch`
218 per `Role`, in `Role` order, the `CrossRoleMatch` behind each
219 role reading `across-roles`, in `Role` order of the role it
220 resolved (empty unless `across-roles` is accepted), and on each
221 side the `Ambiguity` whose other reading the table used, or `None`
222 where that side is read as parsed (always `None` unless
223 `other_readings` is on). A side uses one other reading at a
224 time; each row keeps its own outcome under it.
226 A row is read by its role, a `Role` member or its name
227 (`result["suffix"]`), and `weakest` is the weakest row's outcome.
228 A result has no truth value: `bool(result)` raises TypeError, a
229 conflict being a result too, so test `result.consistent`."""
231 #: Whether nothing in the two names contradicts the match under
232 #: the accepted outcomes.
233 consistent: bool
234 #: One :class:`RoleMatch` per :class:`Role`, in ``Role`` order.
235 roles: tuple[RoleMatch, ...]
236 #: The :class:`CrossRoleMatch` behind each role read
237 #: ``across-roles``, in ``Role`` order of the role it resolved;
238 #: empty unless ``across-roles`` is accepted.
239 across: tuple[CrossRoleMatch, ...] = ()
240 #: The :class:`Ambiguity` whose other reading the table used for the
241 #: left name, or ``None`` where it is read as parsed (always ``None``
242 #: unless ``other_readings`` is on).
243 left_alternative: Ambiguity | None = None
244 #: The same for the right name.
245 right_alternative: Ambiguity | None = None
247 __getstate__ = _guarded_getstate
248 __setstate__ = _guarded_setstate
250 def __post_init__(self) -> None:
251 order = ", ".join(r.value for r in Role)
252 if not isinstance(self.roles, tuple):
253 raise TypeError(
254 f"roles must be a tuple of RoleMatch, one per Role, got "
255 f"{type(self.roles).__name__}; pass tuple(rows)")
256 for row in self.roles:
257 if not isinstance(row, RoleMatch):
258 raise TypeError(
259 f"roles must hold RoleMatch rows, got "
260 f"{type(row).__name__} {row!r}; build each row as "
261 f"RoleMatch(role, outcome, left, right, more)")
262 held = [row.role for row in self.roles]
263 if held != list(Role):
264 raise ValueError(
265 f"roles must hold one RoleMatch per Role, in Role order "
266 f"({order}), got {', '.join(str(r) for r in held) or 'none'}; "
267 f"pass a row for every role, in that order")
269 def __bool__(self) -> bool:
270 """Raises TypeError: a result has no truth value, since a
271 conflict is a result too. Read `consistent`."""
272 raise TypeError(
273 f"a MatchResult has no truth value, got bool() of one whose "
274 f"consistent is {self.consistent}: a conflict is a result "
275 f"too, so `if result:` cannot mean a match; read its "
276 f"consistent field, {_CONSISTENT_HINT}")
278 def __getitem__(self, role: Role | str) -> RoleMatch:
279 """The row of one role: a `Role` member or its name; anything
280 else raises ValueError naming the valid roles."""
281 return self.roles[_RANK_ROLE[_coerce_enum(role, Role, "Role", "roles")]]
283 @property
284 def weakest(self) -> Outcome:
285 """The weakest row's outcome, by `Outcome.strength`."""
286 return _weakest(r.outcome for r in self.roles)
288 def mirrored(self) -> MatchResult:
289 """The same result with the two names swapped: each role's left
290 and right text exchanged and its `more` side flipped, each
291 cross-role match's roles and texts exchanged, and the two sides'
292 alternatives exchanged."""
293 return MatchResult(self.consistent,
294 tuple(m.mirrored() for m in self.roles),
295 tuple(c.mirrored() for c in self.across),
296 self.right_alternative, self.left_alternative)
299#: The outcomes accepted when a caller states none.
300DEFAULT_ACCEPT: frozenset[Outcome] = frozenset({
301 Outcome.SAME, Outcome.FOLDED, Outcome.JOINED, Outcome.LISTED_SPELLING,
302 Outcome.PARTICLES_ASIDE, Outcome.PART_OF_OTHER, Outcome.INITIAL,
303 Outcome.INITIALS_AGREE, Outcome.ONE_SIDE, Outcome.GENERATION_ONE_SIDE,
304 Outcome.NOTED,
305})
307_VALID = ", ".join(o.value for o in Outcome if o is not Outcome.CONFLICT)
308#: The code a refused `accept` is offered: it extends the default set,
309#: which a bare `accept=` would replace, and type-checks.
310_ACCEPT_HINT = ('pass e.g. parser.matching(accept=parser.matching().accept'
311 ' | {"family-initial"})')
312#: The spelling of the other-reading search before it became a switch,
313#: refused with the call that replaces it.
314_OTHER_READING = "other-reading"
315#: The code a refused `other-reading` member is offered; it type-checks.
316_OTHER_READINGS_HINT = "parser.matching(other_readings=True)"
319def _outcome(value: object) -> Outcome:
320 # not _coerce_enum: its message would list `conflict` among the
321 # valid values, which accept refuses
322 if isinstance(value, Outcome):
323 return value
324 if isinstance(value, str):
325 if value == _OTHER_READING:
326 raise ValueError(
327 f"{_OTHER_READING!r} is not an outcome: the search for each "
328 f"side's other readings is a switch; drop it from accept, "
329 f"keep the rest, and pass other_readings=True beside it, "
330 f"e.g. {_OTHER_READINGS_HINT}")
331 try:
332 return Outcome(value)
333 except ValueError:
334 raise ValueError(
335 f"unknown outcome {value!r}; valid outcomes: {_VALID}"
336 ) from None
337 raise TypeError(
338 f"accept must be an iterable of outcome names or Outcome members, "
339 f"got a member {value!r} of type {type(value).__name__}; "
340 f"{_ACCEPT_HINT}")
343@dataclass(frozen=True, slots=True)
344class Matching:
345 """The settings of a name match: the parser that reads the names and
346 the outcomes accepted as consistent, and whether each side's other
347 readings are searched.
349 `accept` takes any iterable of `Outcome` members or their names and is
350 stored as a frozenset with `same` always present. Passing it replaces
351 the default set rather than extending it, so extend the default
352 matcher's set: `parser.matching(accept=parser.matching().accept |
353 {"family-initial"})`. `conflict` cannot be accepted.
355 `other_readings`, a bool, off by default, switches on the search
356 for each side's other readings where the names as parsed are not
357 consistent (see `check`), and the keys of each reading searched
358 (see `keys`). It is not an outcome: no row reads it, and each row
359 keeps its own outcome under the reading used.
360 """
362 parser: Parser
363 accept: frozenset[Outcome] = DEFAULT_ACCEPT
364 other_readings: bool = False
366 __getstate__ = _guarded_getstate
367 __setstate__ = _guarded_setstate
369 def __post_init__(self) -> None:
370 # Parser at call time: _parser imports this module at call time
371 # too, in Parser.matching
372 from nameparser._parser import Parser
373 if not isinstance(self.parser, Parser):
374 raise TypeError(
375 f"parser must be a Parser, got {type(self.parser).__name__}; "
376 f"pass Parser() or use Parser.matching()")
377 accept = self.accept
378 if isinstance(accept, (str, bytes, Mapping)) or not isinstance(accept, Iterable):
379 raise TypeError(
380 f"accept must be an iterable of outcome names, got "
381 f"{type(accept).__name__} {accept!r}; {_ACCEPT_HINT}")
382 outcomes = frozenset(_outcome(v) for v in accept)
383 if Outcome.CONFLICT in outcomes:
384 raise ValueError(
385 f"'conflict' cannot be accepted: it is the outcome of a "
386 f"contradiction; drop it from accept (valid outcomes: "
387 f"{_VALID})")
388 object.__setattr__(self, "accept", outcomes | {Outcome.SAME})
389 if not isinstance(self.other_readings, bool):
390 raise TypeError(
391 f"other_readings must be a bool, got "
392 f"{type(self.other_readings).__name__} "
393 f"{self.other_readings!r}; pass other_readings=True or "
394 f"other_readings=False")
396 def __repr__(self) -> str:
397 added = sorted(o.value for o in self.accept - DEFAULT_ACCEPT)
398 removed = sorted(o.value for o in DEFAULT_ACCEPT - self.accept)
399 if self.other_readings:
400 # a switch, not an outcome, so it follows the outcomes added
401 added.append("other-readings")
402 parts = ["default"]
403 if added:
404 parts.append("+ " + ", ".join(added))
405 if removed:
406 parts.append("- " + ", ".join(removed))
407 return f"Matching({' '.join(parts)}{_parser_repr(self.parser)})"
409 def check(self, a: str | ParsedName, b: str | ParsedName) -> MatchResult:
410 """Compare two names role by role. A string is parsed with this
411 settings object's parser. The result is consistent when every
412 role's outcome is among the accepted ones; `conflict` never is,
413 and an empty family role on either side is a conflict. The
414 check is symmetric: swapping the names gives the mirrored
415 result. It is not transitive: `J. Smith` is consistent with
416 `John Smith` and with `Jane Smith`, which are not consistent
417 with each other.
419 Where `other_readings` is on and the names as parsed are
420 not consistent, each side's other readings are tried too: one
421 per `Ambiguity` with an `alternative`, its words moved to the
422 alternative's role, one ambiguity at a time and never two
423 together, save an alternative into the title or suffix, which
424 is not tried: a title never conflicts and a suffix only on its
425 generation, so the move could only empty a role that does.
426 The table reported is the one with the strongest outcomes, each
427 row keeping its own outcome, and the result names in
428 `left_alternative` and `right_alternative` the ambiguity whose
429 other reading each side used.
431 Where `across-roles` is accepted, a given or family role whose
432 outcome is not accepted is compared with a different role of
433 the other name: a given name with each word of the other's
434 middle name and with its nickname, a family name with the
435 other's maiden name. Only a full name on both sides counts, at
436 `same`, `folded`, `joined` or `listed-spelling`, never an
437 initial. The
438 strongest match resolves the role, which then reads
439 `across-roles`, and is recorded in the result's `across`; a
440 middle word it used is taken out of the middle comparison, the
441 words left compared role to role. No cross-role match is tried
442 where `across-roles` is not accepted. The family role must still
443 agree, here directly or through the maiden name."""
444 left, right = self._parsed(a, "check"), self._parsed(b, "check")
445 best = self._result(left, right)
446 if best.consistent or not self.other_readings:
447 return best
448 # each side's first reading is the name as parsed, so the pair
449 # of those is `best`, already built
450 rights = self._readings(right)
451 candidates = [best, *(
452 self._result(ra, rb, alt_a, alt_b)
453 for ra, alt_a in self._readings(left)
454 for rb, alt_b in rights
455 if alt_a is not None or alt_b is not None)]
456 return min(candidates, key=_strength)
458 def keys(self, name: str | ParsedName) -> frozenset[str]:
459 """Grouping keys, each folded with the transcription digraphs
460 written as their first letter (`_key`: `Doe` keys `do`, and
461 `Müller`, `Mueller` and `Muller` share `muller`): for each word
462 of the folded family base, and
463 each half of a hyphenated one (cut at any of the pipeline's
464 hyphens, each folded to the hyphen-minus) beside its joined and
465 its whole form, a half that is a listed particle left out (`Al-Saud` keys
466 `saud`, `alsaud` and `al-saud`, never `al`), and for the family's
467 whole text, particles kept, folded and joined (`de la Vega` keys
468 `delavega` beside `vega`), one key `word;g` where `g` is the
469 first letter of the given name once joined (empty where there is
470 none; `-Pierre` gives `p`). A word is keyed by every word in its spelling
471 set among surnames (itself and the words it is listed as a
472 spelling of, read as written and folded, each folded), and a
473 given name by the first letter of every word in its set among
474 given names, where a word that is a name of its own as well
475 (`jo`) contributes only itself unless written with its trailing
476 period, the one spelling set the check reads (`_spellings`),
477 and where `familiar-form` is accepted also by the first letter
478 of every name a word of that set is paired with directly as a
479 familiar form, in either direction (`Bill` and `William` each
480 key both `b` and `w`), and where `alternate-spelling` is
481 accepted by that of every name it is paired with as an alternate
482 spelling (`Yuliya` and `Iuliia`).
483 The guarantee rests on this: two words the check
484 reads as listed spellings have sets that meet, so they share a
485 member and with it a key; every family-base word the default
486 check compares is keyed, and so is the whole family joined,
487 which two family names read `joined` share, so two names it finds
488 consistent share a key and grouping by key loses no match. A
489 name with no family has no key.
491 Each accepted opt-in adds the keys its outcome needs:
492 `alternate-spelling` and `familiar-form` the given letters of
493 the paired names (above),
494 `family-initial` a key `f;g` for the first letter `f` of the
495 family's first word, `given-one-side` a bare key for every
496 family part keyed and `across-roles` the maiden name's
497 words without particles as family words, and its whole text
498 joined, and as given letters
499 the first letter of each middle word and of the nickname's
500 first word, save a middle word or a nickname written in
501 initials alone, which the check never matches across roles.
502 Where `other_readings` is on, each other reading `check` tries
503 adds its own keys.
505 A key is a bucket cut from a parse, by one nameparser version
506 under one matcher's settings, not an identifier: a parser that
507 reads the name another way, a release that reads it differently
508 or another accept set gives other keys. Store the names, not
509 their keys, build the keys again after upgrading nameparser or
510 changing the parser or the accepted outcomes, and compare only
511 keys built the same way (decisions/name-matching, 2026-11-13)."""
512 parsed = self._parsed(name, "keys")
513 readings = (self._readings(parsed) if self.other_readings
514 else [(parsed, None)])
515 return frozenset().union(
516 *(self._keys(reading) for reading, _ in readings))
518 def _result(self, left: ParsedName, right: ParsedName,
519 left_alternative: Ambiguity | None = None,
520 right_alternative: Ambiguity | None = None) -> MatchResult:
521 """The table of two readings, each side's alternative the
522 ambiguity whose other reading it is, `None` for a name as
523 parsed."""
524 lexicon = self.parser.lexicon
525 roles = [_compare_role(role, left, right, lexicon, self.accept)
526 for role in Role]
527 resolved, across = self._resolved(roles, left, right)
528 consistent = all(r.outcome in self.accept for r in resolved)
529 # `isupper()` first, a C-level test, so a pair with no given name
530 # in capitals pays no frame for the rule
531 if not consistent and (
532 (left.given.isupper()
533 and _capitals_spelled(left, right, lexicon))
534 or (right.given.isupper()
535 and _capitals_spelled(right, left, lexicon))):
536 # a given word of capitals the other side's names spell
537 # letter for letter reads as those initials, where that
538 # makes the pair consistent and only there, across-roles
539 # included, so it never takes a match away
540 # (decisions/name-matching, 2026-11-13 #1351)
541 spelled = list(roles)
542 for i in (_RANK_ROLE[Role.GIVEN], _MIDDLE):
543 spelled[i] = dataclasses.replace(
544 roles[i], outcome=Outcome.INITIAL,
545 more=_more(roles[i].left, roles[i].right))
546 spelled, spelled_across = self._resolved(spelled, left, right)
547 if all(r.outcome in self.accept for r in spelled):
548 resolved, across, consistent = spelled, spelled_across, True
549 return MatchResult(consistent, tuple(resolved), tuple(across),
550 left_alternative, right_alternative)
552 def _resolved(self, compared: list[RoleMatch], left: ParsedName,
553 right: ParsedName,
554 ) -> tuple[list[RoleMatch], list[CrossRoleMatch]]:
555 """The rows `compared` with each given or family role whose
556 outcome is not accepted resolved across roles (`_pick_across`),
557 a middle word the match used taken out of the middle comparison,
558 and the cross-role matches used; `compared` as it is where
559 `across-roles` is not accepted."""
560 if Outcome.ACROSS_ROLES not in self.accept:
561 return compared, []
562 across: list[CrossRoleMatch] = []
563 roles = list(compared)
564 middles = [_cross_texts(left, Role.MIDDLE),
565 _cross_texts(right, Role.MIDDLE)]
566 for i, r in enumerate(roles):
567 if r.outcome in self.accept or not _RULES[r.role].across:
568 continue
569 found = self._pick_across(r.role, left, right, middles)
570 if found is None:
571 continue
572 cross, index, (rest, la, lb, outcome) = found
573 # the side carrying more is the one whose name held both
574 # the role and the cross role the match used
575 holder = Side.RIGHT if cross.left_role is r.role else Side.LEFT
576 held = r.left if holder is Side.LEFT else r.right
577 roles[i] = dataclasses.replace(
578 r, outcome=Outcome.ACROSS_ROLES,
579 more=holder if held else Side.NEITHER)
580 across.append(cross)
581 if index is not None:
582 # the middle word matched as the given name is
583 # consumed, and the words left compare role to role,
584 # the row keeping both sides' text as parsed
585 middles = rest
586 roles[_MIDDLE] = dataclasses.replace(
587 roles[_MIDDLE], outcome=outcome,
588 more=_row_more(outcome, la, lb))
589 return roles, across
591 def _pick_across(self, role: Role, left: ParsedName, right: ParsedName,
592 middles: list[list[str]],
593 ) -> tuple[CrossRoleMatch, int | None, _MiddleLeft] | None:
594 """The cross-role match `role` takes (`_across`), with the index
595 of the middle word it used and the middle comparison it leaves
596 (`_middle_left`): a match that consumes a middle word leaves the
597 rest to compare, so the matches are ranked by whether that
598 comparison is accepted, then by the match's own outcome, then by
599 that comparison's outcome, then as `_across` orders them, which
600 names no side, so the pick is the same with the names swapped
601 (decisions/name-matching, 2026-11-09 #1263). `middles` holds each
602 side's middle words still to compare."""
603 found = self._across(role, left, right)
604 if not found:
605 return None
606 scored = [(order, cross, index,
607 self._middle_left(middles, cross, index, left, right))
608 for order, (cross, index) in found]
610 def rank(item: tuple[tuple[object, ...], CrossRoleMatch, int | None,
611 _MiddleLeft]) -> tuple[object, ...]:
612 order, cross, _, (_, _, _, middle) = item
613 return (middle not in self.accept, -_STRENGTH[cross.outcome],
614 -_STRENGTH[middle], *order)
615 _, cross, index, left_over = min(scored, key=rank)
616 return cross, index, left_over
618 def _middle_left(self, middles: list[list[str]], cross: CrossRoleMatch,
619 index: int | None, left: ParsedName, right: ParsedName,
620 ) -> _MiddleLeft:
621 """Each side's middle words less the one `cross` used (none
622 where `index` is `None`), both sides' words joined, and the
623 middle row's outcome over them."""
624 rest = [list(words) for words in middles]
625 if index is not None:
626 del rest[0 if cross.left_role is Role.MIDDLE else 1][index]
627 la, lb = (" ".join(words) for words in rest)
628 return rest, la, lb, _role_outcome(
629 _RULES[Role.MIDDLE], la, lb, left, right, self.parser.lexicon,
630 self.accept)
632 def _across(self, role: Role, left: ParsedName, right: ParsedName,
633 ) -> list[tuple[tuple[object, ...],
634 tuple[CrossRoleMatch, int | None]]]:
635 """Every match of `role` on one side against one of its cross
636 roles (its `_RULES` row's `across`) on the other, each with the
637 index of the middle word it used (`None` for a role other than
638 the middle; the match's middle role names the side) and its
639 place in the order that names no side: by outcome, then by the
640 cross role, then by texts. A middle name is read word by word, the other roles
641 whole. Only a full name on both sides counts (`_full_outcome`),
642 never an initial."""
643 lexicon = self.parser.lexicon
644 rule = _RULES[role]
645 found: list[tuple[tuple[object, ...],
646 tuple[CrossRoleMatch, int | None]]] = []
647 for other in rule.across:
648 for lrole, rrole in ((other, role), (role, other)):
649 rights = [(t, _fold(t)) for t in _cross_texts(right, rrole)]
650 for li, la in enumerate(_cross_texts(left, lrole)):
651 fla = _fold(la)
652 for ri, (ra, fra) in enumerate(rights):
653 outcome = _full_outcome(la, ra, fla, fra, lexicon,
654 rule.group)
655 if (outcome is None or outcome not in self.accept
656 or _initials_only(fla) or _initials_only(fra)):
657 continue
658 theirs, mine = (la, ra) if lrole is other else (ra, la)
659 index = (None if other is not Role.MIDDLE
660 else li if lrole is other else ri)
661 found.append((
662 (-_STRENGTH[outcome], _RANK_ROLE[other], theirs, mine),
663 (CrossRoleMatch(lrole, rrole, outcome, la, ra),
664 index)))
665 return found
667 def _readings(self, name: ParsedName
668 ) -> list[tuple[ParsedName, Ambiguity | None]]:
669 """The name as parsed, with no ambiguity, then one other
670 reading per ambiguity whose `alternative` moves a word into a
671 role whose `_RULES` row has `tried_into`: that ambiguity's words
672 moved to the alternative's role by `Parser.revise`, with the
673 ambiguity."""
674 readings: list[tuple[ParsedName, Ambiguity | None]] = [(name, None)]
675 for ambiguity in name.ambiguities:
676 if ambiguity.alternative is None:
677 continue
678 target = ambiguity.alternative.role
679 if not _RULES[target].tried_into:
680 continue
681 words = [t for t in ambiguity.tokens if t.role is not target]
682 if not words:
683 continue
684 moved = frozenset({target, *(t.role for t in words)})
685 # the moved name's texts, read off its own views so a word
686 # a division cut keeps its halves joined
687 laid_out = ParsedName(name.original, tuple(
688 dataclasses.replace(t, role=target, reading=None)
689 if t in words else t for t in name.tokens))
690 readings.append((self.parser.revise(
691 name, **{r.value: getattr(laid_out, r) for r in moved}),
692 ambiguity))
693 return readings
695 def _keys(self, parsed: ParsedName) -> frozenset[str]:
696 lexicon = self.parser.lexicon
697 across = Outcome.ACROSS_ROLES in self.accept
698 family_rule, given_rule = _RULES[Role.FAMILY], _RULES[Role.GIVEN]
699 bases = [parsed.family_base]
700 if across:
701 # the texts the check matches against a family name, each
702 # without its particles as the family base is
703 bases += [_base_of(parsed, other) for other in family_rule.across]
704 forms: list[str] = []
705 for base in bases:
706 forms += _family_words(base, lexicon)
707 # a hyphenated word joined and whole too: either may itself
708 # be the full form another word is listed as a spelling of
709 forms += [form for raw in base.split() if _HYPHENS.search(raw)
710 for form in (_HYPHENS.sub("", raw), raw)]
711 words = set().union(*(_spelling_keys(form, family_rule.group, lexicon)
712 for form in forms if form))
713 # the whole text the check compares a family name by, particles
714 # kept, joined (`La Russa` and `LaRussa` key `larussa`), and under
715 # across-roles each text it compares the family against
716 texts = [parsed.family]
717 if across:
718 texts += [t for other in family_rule.across
719 for t in _cross_texts(parsed, other)]
720 words |= {_key(_joined(_fold(t))) for t in texts if t} - {""}
721 family = parsed.family.split()
722 if family and words and Outcome.FAMILY_INITIAL in self.accept:
723 words |= {f[:1] for f in _spelling_keys(
724 family[0], family_rule.group, lexicon)} - {""}
725 given = _lettered_words(_role_text(parsed, Role.GIVEN))
726 initials: set[str] = set()
727 if given:
728 spellings = _spellings(given[0], given_rule.group, lexicon)
729 # a given letter is the first letter once joined, as the
730 # check compares by `joined` too (`-Pierre` keys `p`, not `-`)
731 initials = _letters_of(_key(_fold(h)) for h in spellings)
732 # every name the check pairs with it as a familiar form or an
733 # alternate spelling, either way (`_paired`), so `Bill` and
734 # `William`, and `Yuliya` and `Iuliia`, share each other's keys
735 for outcome, pairs in _pair_tables(lexicon):
736 if outcome in self.accept:
737 initials |= _letters_of(_paired_forms(spellings, pairs))
738 # no given letter, a name with no given name or one of hyphens
739 # alone, keys the empty letter, as the cross-role letters below
740 # stand beside it rather than for it
741 initials = initials or {""}
742 if across:
743 # the texts the check matches against a given name, each
744 # refused as it refuses them: a cross-role match is never
745 # made by initials alone (`_initials_only`, so `J.-P.` is
746 # not keyed); a text is keyed by its first word's letter
747 for other in given_rule.across:
748 for text in _cross_texts(parsed, other):
749 if not _initials_only(_fold(text)):
750 initials |= _letters_of(_spelling_keys(
751 _lettered_words(text)[0], given_rule.group,
752 lexicon))
753 keys = {f"{w};{g}" for w in words for g in initials}
754 if Outcome.GIVEN_ONE_SIDE in self.accept:
755 keys |= words
756 return frozenset(keys)
758 def _parsed(self, name: object, method: str) -> ParsedName:
759 """`name` parsed, for the public method named, which a refusal
760 names."""
761 if isinstance(name, ParsedName):
762 return name
763 if isinstance(name, str):
764 return self.parser.parse(name)
765 # bytes get the decode hint parse() gives them
766 fix = ("decode first, e.g. raw.decode('utf-8')"
767 if isinstance(name, bytes)
768 else "pass the text, or parser.parse(text)")
769 raise TypeError(
770 f"{method} takes a name string or a ParsedName, got "
771 f"{type(name).__name__} {name!r}; {fix}")
774def _parser_repr(parser: Parser) -> str:
775 """The parser's part of `Matching`'s repr: nothing for a `Parser`
776 reading as `Parser()` does (the default lexicon and policy, no
777 segmenter), the `Parser`'s own bounded repr for any other, and for
778 anything else, a subclass of `Parser` included, or a `Parser`
779 holding a subclass of `Lexicon` or `Policy`, its class name alone,
780 since a subclass's repr and equality may be anything, as `Parser`
781 names a segmenter by its class. A `Parser` missing a field (built
782 past its constructor) is named by its class too, the fields read
783 with `getattr`, so the repr never raises."""
784 # Parser at call time: _parser imports this module at call time
785 from nameparser._parser import Parser
786 missing = object()
787 lexicon, policy, segmenter = (
788 getattr(parser, f, missing) for f in _PARSER_FIELDS)
789 if (type(parser) is not Parser or type(policy) is not Policy
790 or type(lexicon) is not Lexicon or segmenter is missing):
791 return f", parser={type(parser).__name__}"
792 if segmenter is None and policy == Policy() and lexicon == Lexicon.default():
793 return ""
794 return f", parser={parser!r}"
797#: The fields of `Parser` the repr compares with `Parser()`'s, every
798#: field it has (test_match.py holds the two equal, so a field added to
799#: `Parser` is compared or the test fails).
800_PARSER_FIELDS = ("lexicon", "policy", "segmenter")
803# -- the check -------------------------------------------------------------
805#: Every hyphen the pipeline joins two names with in one written word
806#: (rules/O6's set, `_pipeline/_vocab._HYPHEN_CHARS`), each read as the
807#: hyphen-minus: `_fold` maps them, and a raw text is cut at any of them
808#: (`_HYPHENS`), so `Smith‐Jones` (U+2010) and `Thomas–Symonds` (the en
809#: dash) split as `Smith-Jones` does, on both sides and in the keys
810#: (decisions/name-matching, 2026-11-11 #1264).
811_TO_HYPHEN_MINUS = str.maketrans(dict.fromkeys(_HYPHEN_CHARS, "-"))
812#: Spaces and hyphens in a FOLDED text, where every hyphen of
813#: `_HYPHEN_CHARS` is the hyphen-minus already.
814_WORDS = re.compile(r"[\s-]+")
815_RANK_ROLE = {r: i for i, r in enumerate(Role)}
816#: `FULL_STOPS` as the tuple `str.endswith` takes, one test for the
817#: period `_spellings` reads off a word as written.
818_FULL_STOPS = tuple(FULL_STOPS)
819_MIDDLE = _RANK_ROLE[Role.MIDDLE]
820#: The roles `_role_text` parts a run of initials in.
821_RUN_ROLES = frozenset({Role.GIVEN, Role.MIDDLE})
822#: The middle comparison a cross-role match leaves (`_middle_left`): each
823#: side's middle words still to compare, both joined, and the outcome.
824_MiddleLeft = tuple[list[list[str]], str, str, Outcome]
827@functools.lru_cache(maxsize=4096)
828def _forms(text: str) -> frozenset[str]:
829 """The lexicon's forms of a text (`_lexicon._forms`: each letter a
830 keyboard lacks written as typed or as its transcription, letter by
831 letter), each with its hyphens written as the hyphen-minus, as
832 `_fold` writes them."""
833 return frozenset(f.translate(_TO_HYPHEN_MINUS)
834 for f in _lexicon_forms(text))
837def _fold(text: str) -> str:
838 """The lexicon's fold (`_lexicon._fold`: case, accents, full stops
839 and apostrophes), then every hyphen of `_HYPHEN_CHARS` written as
840 the hyphen-minus, so two texts differing by their hyphen character
841 alone are `folded`, as two differing by their apostrophe are."""
842 return _lexicon_fold(text).translate(_TO_HYPHEN_MINUS)
845def _base_of(name: ParsedName, role: Role) -> str:
846 """A role's text without its particles, as `family_base` writes the
847 family's: the maiden's, which the check's maiden row compares
848 (`_compare_maiden`) and `across-roles` keys as family words."""
849 return name._text_for(role, without_tag="particle",
850 unless_tag=UNJOINED_TAG)
853def _cross_texts(name: ParsedName, role: Role) -> list[str]:
854 """The texts of `role` a cross-role match compares: a middle name's
855 words one by one, any other role whole."""
856 if role is Role.MIDDLE:
857 return _role_text(name, role).split()
858 text = _role_text(name, role)
859 return [text] if text else []
862def _role_text(name: ParsedName, role: Role) -> str:
863 """The text of `role` the name match reads: the field as written,
864 save that in the given and middle names two initials written with
865 nothing between them are two words, as rules/T7 parts a given name
866 written as a run of initials ('J.R.R. Tolkien' has the middle names
867 'R. R.', the field writing them 'R.R.'), so each compares as the
868 initial it is. A run T7 leaves whole, as in the middle names of
869 'John E.T. Smith', is one token and compares as one word, though
870 `initials()` reads it letter by letter (rules/R3) -- decisions/T7
871 (#1296)."""
872 text: str = getattr(name, role)
873 if role not in _RUN_ROLES or "." not in text:
874 return text
875 words: list[str] = []
876 end = -1
877 initial = False
878 for tok in name.tokens_for(role):
879 joined = tok.span is not None and tok.span.start == end
880 if words and joined and not (initial and "initial" in tok.tags):
881 words[-1] += tok.text
882 else:
883 words.append(tok.text)
884 end = -1 if tok.span is None else tok.span.end
885 initial = "initial" in tok.tags
886 return " ".join(words)
889def _strength(result: MatchResult) -> tuple[object, ...]:
890 """The order `check` picks a table by, best first: consistent, then
891 the weakest outcome strongest (then the next weakest, and so on),
892 then fewer sides read another way, then each role's text pair, each
893 cross-role match's and the two alternatives, each pair taken
894 without its sides, which keeps the pick the same with the names
895 swapped."""
896 alternatives = (result.left_alternative, result.right_alternative)
897 ranks = sorted((-_STRENGTH[r.outcome] for r in result.roles),
898 reverse=True)
899 sides = sum(a is not None for a in alternatives)
900 texts = tuple(tuple(sorted((r.left, r.right))) for r in result.roles)
901 across = tuple(sorted(((c.left, c.left_role), (c.right, c.right_role)))
902 for c in result.across)
903 return (not result.consistent, ranks, sides, texts, across,
904 sorted(_ambiguity_key(a) for a in alternatives))
907def _ambiguity_key(ambiguity: Ambiguity | None) -> tuple[str, ...]:
908 """An ambiguity as sortable text, `()` for none."""
909 if ambiguity is None:
910 return ()
911 alternative = ambiguity.alternative
912 return (ambiguity.kind.value, ambiguity.detail,
913 repr([(t.text, t.span) for t in ambiguity.tokens]),
914 alternative.role.value if alternative is not None else "")
917def _weakest(outcomes: Iterable[Outcome]) -> Outcome:
918 return min(outcomes, key=_STRENGTH.__getitem__)
921def _letters(text: str) -> int:
922 return sum(c.isalnum() for c in _fold(text))
925def _more(left: str, right: str) -> Side:
926 if left == right:
927 return Side.NEITHER
928 a, b = _letters(left), _letters(right)
929 return Side.LEFT if a > b else Side.RIGHT if b > a else Side.NEITHER
932def _row_more(outcome: Outcome, a: str, b: str) -> Side:
933 """A row's side carrying more: neither on a conflict."""
934 return Side.NEITHER if outcome is Outcome.CONFLICT else _more(a, b)
937def _letters_of(words: Iterable[str]) -> set[str]:
938 """The given letters (`_letter`) of folded words, a word of
939 hyphens alone giving none."""
940 return {_letter(w) for w in words} - {""}
943def _is_initial(folded: str) -> bool:
944 """A folded text is one letter, outside rules/R7's scripts that
945 write no initials (_policy._SCRIPT_PROPERTIES), where a single
946 character is a whole word."""
947 return (len(folded) == 1 and folded.isalpha()
948 and not in_initialless_script(folded))
951def _spellings(word: str, group: str, lexicon: Lexicon) -> frozenset[str]:
952 """The words `word` is a listed spelling of in `group`, the word
953 itself included, read from the word as written and from it folded,
954 each member beside its folded form: `Jose` among given names reaches
955 `jo`'s full form `josé` folded, so `Jo.` and `Jose` meet. A word that
956 is a name of its own as well reaches its links only written with
957 its trailing period, any full stop the vocabulary strips
958 (`FULL_STOPS`, `Jo.` too), read here off the word as written since
959 both the normalizing and the fold drop it: `Jo` is the given name Jo
960 alone (decisions/name-matching, 2026-11-08 #1006 follow-up)."""
961 period = word.endswith(_FULL_STOPS)
962 heads = (lexicon._headwords(word, group, period=period)
963 | lexicon._headwords(_fold(word), group, period=period))
964 # a written-out spelling of a letter a keyboard lacks meets the
965 # word written with it (`_forms`)
966 return heads | {f for h in heads | {word} for f in _forms(h)}
969#: The transcription digraphs a key writes as their first letter, so every
970#: form of a text (`_forms`) cuts one key: `muller` for `Müller`,
971#: `Mueller` and `Muller` alike. A key need only be shared by the texts
972#: the check matches, so a coarser key keeps the guarantee and gives a
973#: name one key where its forms number 2^k (#1379); the rules
974#: are confluent, so the result is one whatever order they apply in.
975_KEY_DIGRAPHS = re.compile(r"ae|oe|ue|aa|dj")
978def _key(folded: str) -> str:
979 """A folded text as a key: every transcription digraph written as its
980 first letter, until none is left (`aae` is `a`)."""
981 while True:
982 shorter = _KEY_DIGRAPHS.sub(lambda m: m.group(0)[0], folded)
983 if shorter == folded:
984 return folded
985 folded = shorter
988def _spelling_keys(word: str, group: str, lexicon: Lexicon) -> set[str]:
989 """The folded members of `word`'s spelling set in `group`, which
990 `keys` cuts its keys from: every spelling set holds each member's
991 folded form, so two sets that meet share a folded member. `_fold` is
992 idempotent (test_match.py holds it over every assigned code point,
993 alone and beside letters, hyphens and combining marks), so the
994 folded members are the folds of `_spellings`' own."""
995 return {_key(_fold(h)) for h in _spellings(word, group, lexicon)}
998def _listed(a: str, b: str, group: str, lexicon: Lexicon) -> bool:
999 """Two words are listed spellings of one word in `group`: their
1000 spelling sets meet."""
1001 return not _spellings(a, group, lexicon).isdisjoint(
1002 _spellings(b, group, lexicon))
1005def _part_agrees(a: str, b: str, lexicon: Lexicon,
1006 group: str) -> Outcome | None:
1007 """One word against one word: `same` where they are equal once
1008 folded or listed as one spelling in `group`, `initial` where one is
1009 an initial of the other's first letter, else `None`. A hyphenated
1010 word is compared part by part against the other's hyphen-split
1011 parts (`J.-P.` / `Jean-Pierre`), cut at any of the pipeline's
1012 hyphens."""
1013 fa, fb = _fold(a), _fold(b)
1014 if fa == fb or _listed(a, b, group, lexicon):
1015 return Outcome.SAME
1016 if (_is_initial(fa) and fb[:1] == fa) or (_is_initial(fb) and fa[:1] == fb):
1017 return Outcome.INITIAL
1018 pa, pb = _HYPHENS.split(a), _HYPHENS.split(b)
1019 if len(pa) > 1 and len(pa) == len(pb):
1020 parts = [_part_agrees(x, y, lexicon, group) for x, y in zip(pa, pb)]
1021 if None not in parts:
1022 return _weakest(p for p in parts if p is not None)
1023 return None
1026def _pair_tables(lexicon: Lexicon,
1027 ) -> tuple[tuple[Outcome, Callable[[str], frozenset[str]]],
1028 ...]:
1029 """Each opt-in that pairs two given names, with the lexicon's
1030 table of its pairs: the familiar forms and the alternate spellings."""
1031 return ((Outcome.FAMILIAR_FORM, lexicon._familiar_forms),
1032 (Outcome.ALTERNATE_SPELLING, lexicon._alternate_spellings))
1035def _paired_forms(spellings: frozenset[str],
1036 pairs: Callable[[str], frozenset[str]]) -> set[str]:
1037 """The given names any member of a spelling set is paired with
1038 directly by `pairs` (`_pair_tables`), in either direction, each as
1039 normalized and in every folded form (`_forms`)."""
1040 paired = {name for word in spellings for name in pairs(word)}
1041 return paired | {f for name in paired for f in _forms(name)}
1044def _paired(sa: frozenset[str], sb: frozenset[str],
1045 pairs: Callable[[str], frozenset[str]]) -> bool:
1046 """Two given-name words, by their spelling sets, are a pair in
1047 `pairs` (`Bill` / `William` a familiar form, `Yuliya` / `Iuliia` an
1048 alternate spelling): a name one word's spelling set is paired with
1049 directly meets the other's spelling set. Read whichever way the pair
1050 was written, since the vocabulary writes a familiar pair on its
1051 shorter name, which is not always the familiar form (`charles` /
1052 `charlie`), and a caller may write either, and never chained, so two
1053 longer names paired with one short name (`Maximilian` / `Maxwell`)
1054 are no pair. Symmetric in its two arguments by construction: the
1055 lexicon pairs each name both ways and under its fold as well
1056 (`Lexicon._familiar_forms`), and a spelling set holds each member's
1057 fold, so asking from the second side finds nothing the first does
1058 not (measured over every pair of the 1,034 familiar names the
1059 default shipped and their folds, 2026-11-08)."""
1060 return not _paired_forms(sa, pairs).isdisjoint(sb)
1063def _familiar_outcome(wa: list[str], wb: list[str], lexicon: Lexicon,
1064 accept: frozenset[Outcome]) -> Outcome | None:
1065 """Two given texts' words, pair by pair, each the same once folded,
1066 a listed spelling, an alternate spelling or a familiar form, and at
1067 least one of the last two: `alternate-spelling` where every such pair
1068 is one, `familiar-form` where every one is a familiar form, and
1069 where some need one and some the other, `familiar-form` where the
1070 caller accepts both and otherwise the one they do not accept, so a
1071 pair needing an unaccepted leniency is never accepted on the other
1072 (decisions/name-matching, 2026-11-12 ALTERNATE SPELLINGS ARE
1073 OPT-IN). `None` where no pair needed either or one is neither."""
1074 if len(wa) != len(wb):
1075 return None
1076 alts: list[bool] = []
1077 fams: list[bool] = []
1078 for x, y in zip(wa, wb):
1079 if _fold(x) == _fold(y):
1080 continue
1081 sx, sy = _spellings(x, "given", lexicon), _spellings(y, "given", lexicon)
1082 if not sx.isdisjoint(sy):
1083 continue
1084 alts.append(_paired(sx, sy, lexicon._alternate_spellings))
1085 fams.append(_paired(sx, sy, lexicon._familiar_forms))
1086 if not (alts[-1] or fams[-1]):
1087 return None
1088 if not alts:
1089 return None
1090 alt, fam = Outcome.ALTERNATE_SPELLING, Outcome.FAMILIAR_FORM
1091 holding = [o for o, every in ((alt, all(alts)), (fam, all(fams)))
1092 if every]
1093 accepted = [o for o in holding if o in accept]
1094 if accepted:
1095 return accepted[0]
1096 if holding:
1097 return holding[0]
1098 # some pairs need an alternate spelling, others a familiar form
1099 return fam if alt in accept else alt
1102def _lettered_words(text: str) -> list[str]:
1103 """A text's words from the first that is not hyphens or full stops
1104 alone: the word a given letter is cut from, since `joined` reads
1105 `- Pierre` as `Pierre`; all of them where none is (decisions/
1106 name-matching, 2026-11-09 #1261)."""
1107 words = text.split()
1108 for i, word in enumerate(words):
1109 if _joined(_fold(word)):
1110 return words[i:]
1111 return words
1114def _letter(folded: str) -> str:
1115 """A folded word's first letter once joined, the given letter a key
1116 is cut on; empty for a word of hyphens alone."""
1117 return _joined(folded)[:1]
1120def _joined(folded: str) -> str:
1121 """A folded text without its spaces and hyphens (the fold writes
1122 each as the hyphen-minus), the form `joined`
1123 compares and the keys cut a family's whole key from (decisions/
1124 name-matching, 2026-11-09 #1261)."""
1125 return _WORDS.sub("", folded)
1128def _initials_only(folded: str) -> bool:
1129 """A folded text is initials alone."""
1130 return all(_is_initial(w) for w in _WORDS.split(folded) if w)
1133def _capitals_spelled(name: ParsedName, other: ParsedName,
1134 lexicon: Lexicon) -> bool:
1135 """`name`'s given name is one word of two or three capital letters
1136 (`JP`, `_capitals_word`), it has no middle name, and its given or
1137 family name holds a lower-case letter (a title, suffix, nickname or
1138 maiden name in mixed case leaves `Dr. JP SMITH` in capitals, the
1139 maiden name being another name's writing), and `other` spells those
1140 letters exactly, in order: its given name one word agreeing with the
1141 first letter and its middle names as many words as the letters left,
1142 each agreeing with its letter, as `_part_agrees` reads an initial
1143 (`JP Smith` / `John Paul Smith`). The words are counted as the
1144 comparison of the name written with full stops (`J. P. Smith`)
1145 counts them, role by role, so a given name of two words (`Abdul
1146 Adil`, a bound pair) spells no letter; and a word of `other` that
1147 is a capitals word itself spells no letter either, being initials
1148 by this same reading (`JR Paul Smith` spells J, R, P, not J, P), so
1149 it never stands in for a name the caller's outcomes refuse
1150 (decisions/name-matching, 2026-11-13 #1351)."""
1151 given = _role_text(name, Role.GIVEN).split()
1152 if len(given) != 1 or _role_text(name, Role.MIDDLE):
1153 return False
1154 word = unicodedata.normalize("NFC", given[0])
1155 if not _capitals_word(word):
1156 return False
1157 if not any(c.islower() for role in (Role.GIVEN, Role.FAMILY)
1158 for c in getattr(name, role)):
1159 return False
1160 theirs = _role_text(other, Role.GIVEN).split()
1161 middle = _role_text(other, Role.MIDDLE).split()
1162 if len(theirs) != 1 or len(middle) != len(word) - 1:
1163 return False
1164 return all(not _capitals_word(unicodedata.normalize("NFC", w))
1165 and _part_agrees(letter, w, lexicon, "given") is not None
1166 for letter, w in zip(word, theirs + middle))
1169def _capitals_word(word: str) -> bool:
1170 """A word of two or three capital letters (`JP`), which
1171 `_capitals_spelled` reads as initials: given NFC-composed."""
1172 return 2 <= len(word) <= 3 and word.isalpha() and word.isupper()
1175def _same_letters(fa: str, fb: str) -> bool:
1176 """Two folded texts of initials alone hold the same letters in
1177 order, a word of hyphens or full stops alone left out (`J.-` / `J.`):
1178 the test a family or maiden name of initials alone reads, where the
1179 given, middle and nickname rows keep an empty word
1180 (`_initial_outcome`)."""
1181 return ([w for w in _WORDS.split(fa) if w]
1182 == [w for w in _WORDS.split(fb) if w])
1185def _initials_alone(fa: str, fb: str) -> bool:
1186 """Two folded texts are both initials alone: `joined` leaves them to
1187 `initials-agree`, and a family or maiden name of them reads nothing
1188 else (`_text_outcomes`)."""
1189 return _initials_only(fa) and _initials_only(fb)
1192def _full_outcome(a: str, b: str, fa: str, fb: str, lexicon: Lexicon,
1193 group: str) -> Outcome | None:
1194 """Two non-empty texts, `fa` and `fb` their folded forms, as full
1195 names: same, folded, joined (equal once folded and stripped of
1196 spaces and hyphens, `La Russa` / `LaRussa`, unless both are initials
1197 alone), or listed spelling (word by word, in the role's `same_as`
1198 `group`), else `None`."""
1199 if a == b:
1200 return Outcome.SAME
1201 forms_a, forms_b = _forms(a), _forms(b)
1202 if fa == fb or not forms_a.isdisjoint(forms_b):
1203 return Outcome.FOLDED
1204 if not {_joined(f) for f in forms_a}.isdisjoint(
1205 {_joined(f) for f in forms_b}) and not _initials_alone(fa, fb):
1206 # two texts of initials alone are `initials-agree`'s to read
1207 return Outcome.JOINED
1208 wa, wb = a.split(), b.split()
1209 if len(wa) == len(wb) and all(
1210 _listed(x, y, group, lexicon) for x, y in zip(wa, wb)):
1211 return Outcome.LISTED_SPELLING
1212 return None
1215def _text_outcomes(a: str, b: str, lexicon: Lexicon, group: str,
1216 bases: tuple[str, str] | None, chain: bool,
1217 accept: frozenset[Outcome]) -> Iterator[Outcome]:
1218 """The outcomes that hold for two non-empty texts of one role,
1219 strongest first, lazily, and last conflict, which always holds. An
1220 outcome holds only where the leniency it names was needed: none is
1221 yielded where a stronger one that implies it holds, nor in the
1222 family role after the first of its chain (decisions/name-matching,
1223 2026-11-08 FAMILIAR FORMS, the review's ruling 1).
1225 - A full-name outcome (`_full_outcome`: same, folded, joined,
1226 listed spelling) implies every weaker one, two texts equal once folded
1227 or listed as one needing no other leniency, so it is the only
1228 outcome yielded. `joined` is the exception: two texts equal once
1229 their spaces and hyphens go may still need the weaker leniencies
1230 read their words apart (`De La Cruz` / `Dela Cruz`, its particles
1231 set aside), so they are yielded after it, and a caller who does
1232 not accept `joined` keeps what they accepted before it
1233 (decisions/name-matching, 2026-11-09 #1261).
1234 - Given `bases`, the family role's (`_compare_family`) or the maiden
1235 name's (`_compare_maiden`), two texts of initials alone read
1236 `initials-agree` where their letters agree in order and nothing
1237 else: `family-initial` and `initial` ask whether an initial stands
1238 for a word on the other side, and there is none, and
1239 `particles-aside` and `part-of-other` would admit a reorder or a
1240 subset of the letters (`J. P.` / `P. J.`, `J.` / `J. P.`; decisions/
1241 name-matching, 2026-11-13 #1350).
1242 - Given `bases`, the family role's, the other outcomes are
1243 treated as one chain, particles set aside, part of the other,
1244 family initial, and the first that holds is the
1245 only one yielded. They are not all implied by the one before:
1246 part of the other and family initial are independent leniencies
1247 (`John S.` / `John S.-Jones` holds both), so a pair holding an
1248 unaccepted part of the other is refused even where family
1249 initial holds and is accepted.
1250 - In any other role, initial against name and initials agree are
1251 one leniency, the first that holds of the two yielded; a familiar
1252 form (in the `given` group) and a hyphenated part are each
1253 orthogonal to it and to each other, so each is yielded where it
1254 holds (`Jean` / `Jean-Paul`, a caller's familiar pair and a
1255 hyphenated part both).
1256 - Given `bases` and not `chain`, the maiden name's
1257 (`_compare_maiden`), the two leniencies that read the bases,
1258 particles set aside then part of the other, the first that holds,
1259 are yielded ahead of any other role's, so the maiden name sets its
1260 particles aside as the family name does while an initial against
1261 it still reads `initial`, never the opt-in `family-initial`, and
1262 a hyphenated part is still yielded beside part of the other: a
1263 caller keeps every maiden outcome they accepted before
1264 (decisions/name-matching, 2026-11-11 #1264)."""
1265 fa, fb = _fold(a), _fold(b)
1266 full = _full_outcome(a, b, fa, fb, lexicon, group)
1267 wa, wb = a.split(), b.split()
1268 if full is not None:
1269 yield full
1270 if full is None or full is Outcome.JOINED:
1271 if bases is not None and _initials_alone(fa, fb):
1272 # a family or maiden name of initials alone on both sides
1273 # agrees letter for letter, in order, or not at all: an
1274 # initial stands for a word, and the other side holds none
1275 # for it to stand for (decisions/name-matching, 2026-11-13
1276 # #1350)
1277 if _same_letters(fa, fb):
1278 yield Outcome.INITIALS_AGREE
1279 elif bases is not None and chain:
1280 first = _family_outcome(wa, wb, fa, fb, bases, lexicon, group)
1281 if first is not None:
1282 yield first
1283 else:
1284 if bases is not None and (
1285 aside := _aside_outcome(bases, lexicon, group)) is not None:
1286 yield aside
1287 initials = _initial_outcome(wa, wb, fa, fb, lexicon, group)
1288 if initials is not None:
1289 yield initials
1290 if group == "given" and (familiar := _familiar_outcome(
1291 wa, wb, lexicon, accept)) is not None:
1292 yield familiar
1293 if len(wa) == len(wb) == 1 and (
1294 any(_first_half(x, y) or _first_half(y, x)
1295 for x in _forms(a) for y in _forms(b))):
1296 yield Outcome.HYPHENATED_PART
1297 yield Outcome.CONFLICT
1300def _initial_outcome(wa: list[str], wb: list[str], fa: str, fb: str,
1301 lexicon: Lexicon, group: str) -> Outcome | None:
1302 """Two texts' words, as `wa` and `wb`, folded whole as `fa` and
1303 `fb`: `initial` where every pair agrees and one is an initial of
1304 its name, else `initials-agree` where both are initials alone and
1305 the same ones, else `None`."""
1306 if len(wa) == len(wb):
1307 parts = [_part_agrees(x, y, lexicon, group) for x, y in zip(wa, wb)]
1308 if None not in parts and Outcome.INITIAL in parts:
1309 return Outcome.INITIAL
1310 # exact words here, an empty one kept: a stray hyphen in a given,
1311 # middle or nickname spells a word, where the family and maiden
1312 # names' branch leaves it out (`_same_letters`)
1313 if _initials_alone(fa, fb) and _WORDS.split(fa) == _WORDS.split(fb):
1314 return Outcome.INITIALS_AGREE
1315 return None
1318def _family_outcome(wa: list[str], wb: list[str], fa: str, fb: str,
1319 bases: tuple[str, str], lexicon: Lexicon,
1320 group: str) -> Outcome | None:
1321 """The family role's chain (`_text_outcomes`), the first that
1322 holds: `_aside_outcome`'s two leniencies, then an initial against
1323 the family name (family initial). Two family names of initials alone
1324 never reach it. A listed spelling counts inside a compound surname as
1325 it does whole, in `group` (`Smyth-Jones` / `Smith` with `smyth`
1326 listed as `smith`; decisions/name-matching, 2026-11-09 #1262)."""
1327 aside = _aside_outcome(bases, lexicon, group)
1328 if aside is not None:
1329 return aside
1330 if _initial_outcome(wa, wb, fa, fb, lexicon, group) is Outcome.INITIAL:
1331 return Outcome.FAMILY_INITIAL
1332 return None
1335def _aside_outcome(bases: tuple[str, str], lexicon: Lexicon,
1336 group: str) -> Outcome | None:
1337 """The two leniencies that read two bases (the texts without their
1338 particles), the first that holds: the bases equal once folded or
1339 listed as spellings word for word (particles set aside), or one
1340 base's words each among the other's or listed as a spelling of one
1341 of them (part of the other), else `None`."""
1342 spellings = _SpellingSets(lexicon, group)
1343 if bases[0] and _bases_agree(bases[0], bases[1], spellings):
1344 return Outcome.PARTICLES_ASIDE
1345 wa, wb = _base_forms(bases[0], lexicon), _base_forms(bases[1], lexicon)
1346 if wa and wb and (_covered(wa, wb, spellings) or _covered(wb, wa, spellings)):
1347 return Outcome.PART_OF_OTHER
1348 return None
1351def _pick(outcomes: Iterable[Outcome], accept: frozenset[Outcome]) -> Outcome:
1352 """The outcome a row reports: the strongest that holds and is
1353 accepted, else, where none of those holding is accepted, the
1354 strongest that holds, so an unaccepted outcome still says what the
1355 pair needed (`Jack` / `John` reads `familiar-form` under the
1356 default) and an accepted weaker one is never hidden behind it
1357 (decisions/name-matching, 2026-11-08 FAMILIAR FORMS). `outcomes`
1358 run strongest first and end in `conflict`, never accepted."""
1359 holding = iter(outcomes)
1360 strongest = next(holding)
1361 if strongest in accept:
1362 return strongest
1363 return next((o for o in holding if o in accept), strongest)
1366def _text_outcome(a: str, b: str, lexicon: Lexicon, group: str,
1367 accept: frozenset[Outcome],
1368 bases: tuple[str, str] | None = None,
1369 chain: bool = True) -> Outcome:
1370 """Two non-empty texts of one role, by `_pick` over the outcomes
1371 that hold (`_text_outcomes`)."""
1372 return _pick(_text_outcomes(a, b, lexicon, group, bases, chain, accept),
1373 accept)
1376def _particle_half(folded: str, lexicon: Lexicon) -> bool:
1377 """A folded half of a hyphenated family word that is a listed
1378 particle (`al` in `Al-Saud`): set aside like a spaced particle, so it
1379 is neither a family-base word for `part-of-other` nor a key."""
1380 # _normalize is the lexicon's own key normalizer, so the half is
1381 # looked up as the particle set's keys are written
1382 return _normalize(folded) in lexicon._sets.particles
1385def _family_words(base: str, lexicon: Lexicon) -> list[str]:
1386 """A family base's comparable words, as written: each word, and a
1387 hyphenated one as its halves less any listed particle, an empty half
1388 dropped, a word cut at any of the pipeline's hyphens (`_HYPHENS`).
1389 Read by `part-of-other` (`_base_forms`) and by `keys`, so
1390 the two set aside the same halves. Raw and folded agree half for
1391 half: `_fold` never adds or removes a hyphen or a space, writing each
1392 hyphen as the hyphen-minus (test_match.py holds it over every
1393 assigned code point in context), so a word's
1394 halves fold to its folded halves, save that a word or half of full
1395 stops folds to empty."""
1396 words: list[str] = []
1397 for word in base.split():
1398 halves = _HYPHENS.split(word)
1399 if len(halves) > 1:
1400 words += [h for h in halves
1401 if h and not _particle_half(_fold(h), lexicon)]
1402 else:
1403 words.append(word)
1404 return words
1407def _base_forms(base: str, lexicon: Lexicon) -> list[tuple[str, str]]:
1408 """The family-base words `part-of-other` compares, each as written
1409 and folded, a word that folds to empty left out."""
1410 return [(w, f) for w in _family_words(base, lexicon) if (f := _fold(w))]
1413class _SpellingSets:
1414 """Each word's spelling set in one group (`_spellings`), built once
1415 per family comparison: the two leniencies ask a word's set against
1416 several others, and a set takes two `Lexicon._headwords` searches."""
1418 __slots__ = ("_lexicon", "_group", "_sets")
1420 def __init__(self, lexicon: Lexicon, group: str) -> None:
1421 self._lexicon, self._group = lexicon, group
1422 self._sets: dict[str, frozenset[str]] = {}
1424 def of(self, word: str) -> frozenset[str]:
1425 found = self._sets.get(word)
1426 if found is None:
1427 found = self._sets[word] = _spellings(word, self._group,
1428 self._lexicon)
1429 return found
1431 def listed(self, a: str, b: str) -> bool:
1432 """`_listed`, from the sets already built."""
1433 return not self.of(a).isdisjoint(self.of(b))
1436def _bases_agree(a: str, b: str, spellings: _SpellingSets) -> bool:
1437 """Two family bases are equal once folded, or of as many words, each
1438 pair equal once folded or listed as one spelling in the group."""
1439 if _fold(a) == _fold(b):
1440 return True
1441 wa, wb = a.split(), b.split()
1442 return len(wa) == len(wb) and all(
1443 _fold(x) == _fold(y) or spellings.listed(x, y)
1444 for x, y in zip(wa, wb))
1447def _covered(words: list[tuple[str, str]], others: list[tuple[str, str]],
1448 spellings: _SpellingSets) -> bool:
1449 """Every word of `words` is among `others` once folded, or listed as
1450 a spelling of one of them in the group; each a (written, folded)
1451 pair."""
1452 folded = {f for _, f in others}
1453 return all(f in folded or any(spellings.listed(w, o) for o, _ in others)
1454 for w, f in words)
1457def _first_half(w: str, hyphenated: str) -> bool:
1458 """The folded word `w` is the first half of the folded `hyphenated`
1459 (`hong` / `hong-yi`): the first half only, which shares the given
1460 initial a key is cut on."""
1461 parts = hyphenated.split("-")
1462 return len(parts) > 1 and bool(w) and parts[0] == w
1465def _middle_outcome(a: str, b: str, lexicon: Lexicon,
1466 accept: frozenset[Outcome], group: str) -> Outcome:
1467 """The middle role word by word, in order: each aligned pair by
1468 `_text_outcome` in `group`, each word past the shorter side
1469 one-sided, the role taking the weakest; `same` where both are
1470 empty. Where one side holds more words, the shorter side's words
1471 may instead align, in order, with any of the longer side's, every
1472 aligned pair accepted and the words left over one-sided (`Beth` /
1473 `Anne Beth`); the accepted one of that alignment and the
1474 left-aligned reading is taken, or where both or neither are, the
1475 stronger, so accepting more never weakens the middle row compared
1476 on its own
1477 (decisions/name-matching, 2026-11-09 #1263). Two middle names of
1478 as many words compare pair by pair."""
1479 wa, wb = a.split(), b.split()
1480 if not wa and not wb:
1481 return Outcome.SAME
1482 outcomes = [_text_outcome(x, y, lexicon, group, accept)
1483 for x, y in zip(wa, wb)]
1484 if len(wa) == len(wb):
1485 return _combined(outcomes, accept)
1486 left = _one_sided(_combined(outcomes, accept), accept)
1487 short, long = (wa, wb) if len(wa) < len(wb) else (wb, wa)
1488 aligned = _subsequence_outcome(short, long, lexicon, group, accept)
1489 if aligned is None:
1490 return left
1491 aligned = _one_sided(aligned, accept)
1492 # an accepted reading over one that is not, else the stronger, as a
1493 # row reports the strongest outcome that holds and is accepted, else
1494 # the strongest that holds (`_pick`)
1495 if (aligned in accept) != (left in accept):
1496 return aligned if aligned in accept else left
1497 return aligned if _STRENGTH[aligned] > _STRENGTH[left] else left
1500def _combined(outcomes: list[Outcome],
1501 accept: frozenset[Outcome]) -> Outcome:
1502 """The words' outcomes as one: the weakest, save where a word's
1503 outcome is not accepted, when the weakest of those, so an accepted
1504 weaker outcome (`familiar-form`) never hides a stronger one the
1505 caller does not accept (`alternate-spelling`, `hyphenated-part`), as
1506 `_one_sided` keeps it from hiding the one-sided word."""
1507 refused = [o for o in outcomes if o not in accept]
1508 return _weakest(refused or outcomes)
1511def _one_sided(outcome: Outcome, accept: frozenset[Outcome]) -> Outcome:
1512 """`outcome` with a word left over on one side: the weaker of it and
1513 `one-side`, and `one-side` itself where the caller does not accept
1514 it, so an accepted outcome weaker than it (`familiar-form`) never
1515 hides the one-sided word."""
1516 weakest = _weakest((outcome, Outcome.ONE_SIDE))
1517 if Outcome.ONE_SIDE not in accept and weakest in accept:
1518 return Outcome.ONE_SIDE
1519 return weakest
1522def _subsequence_outcome(short: list[str], long: list[str], lexicon: Lexicon,
1523 group: str, accept: frozenset[Outcome],
1524 ) -> Outcome | None:
1525 """The strongest weakest outcome over the in-order alignments of
1526 every word of `short` with words of `long`, each aligned pair's
1527 outcome accepted; `None` where no such alignment exists. Word `i`
1528 of `short` can only align with words `i` to `i + slack` of `long`,
1529 so only that band is compared."""
1530 slack = len(long) - len(short)
1531 # best[i, j]: the strongest weakest outcome aligning short[i:] into
1532 # long[j:], or None; only cells with 0 <= j - i <= slack are read
1533 best: dict[tuple[int, int], Outcome | None] = {}
1534 for i in range(len(short), -1, -1):
1535 for j in range(i + slack, i - 1, -1):
1536 if i == len(short):
1537 best[i, j] = Outcome.SAME
1538 continue
1539 found = best[i, j + 1] if j < i + slack else None
1540 outcome = _text_outcome(short[i], long[j], lexicon, group, accept)
1541 if outcome in accept:
1542 rest = best[i + 1, j + 1]
1543 if rest is not None:
1544 here = _weakest((outcome, rest))
1545 if found is None or _STRENGTH[here] > _STRENGTH[found]:
1546 found = here
1547 best[i, j] = found
1548 return best[0, 0]
1551def _noted(a: str, b: str, lexicon: Lexicon, group: str,
1552 accept: frozenset[Outcome]) -> Outcome:
1553 """A role that never conflicts: equal by any spelling the caller
1554 accepts, else noted, so a caller who does not accept `folded` or
1555 `joined` reads `noted` rather than an outcome they refuse
1556 (decisions/name-matching, 2026-11-09 #1261)."""
1557 if not a and not b:
1558 return Outcome.SAME
1559 if a and b:
1560 full = _full_outcome(a, b, _fold(a), _fold(b), lexicon, group)
1561 if full is not None and full in accept:
1562 return full
1563 return Outcome.NOTED
1566def _suffix_outcome(left: ParsedName, right: ParsedName,
1567 lexicon: Lexicon, group: str,
1568 accept: frozenset[Outcome]) -> Outcome:
1569 """A different generation conflicts and one on one side only is its
1570 own outcome, whatever credentials either side carries; where the
1571 generations agree, the rest of the suffix (credentials, honorifics)
1572 is noted. Listed spellings are read in `group`."""
1573 if left.suffix == right.suffix:
1574 return Outcome.SAME
1575 ga, gb = left.generation, right.generation
1576 if ga and gb:
1577 full = _full_outcome(ga, gb, _fold(ga), _fold(gb), lexicon, group)
1578 if full is None:
1579 return Outcome.CONFLICT
1580 generation = full
1581 elif ga or gb:
1582 return Outcome.GENERATION_ONE_SIDE
1583 else:
1584 generation = Outcome.SAME
1585 rest = _noted(" ".join(filter(None, (left.credentials, left.honorifics))),
1586 " ".join(filter(None, (right.credentials, right.honorifics))),
1587 lexicon, group, accept)
1588 return _weakest((generation, rest))
1591#: A role's comparator: its two texts, the two names they come from, the
1592#: lexicon, the accepted outcomes and the role's own rule.
1593_Compare = Callable[
1594 [str, str, ParsedName, ParsedName, Lexicon, frozenset[Outcome], "_RoleRule"],
1595 Outcome]
1598@dataclass(frozen=True, slots=True)
1599class _RoleRule:
1600 """How one role compares, read by the check's row for the role, the
1601 cross-role and other-reading searches and the keys (#1260). The
1602 word-by-word reading of a middle name (`_cross_texts`,
1603 `_middle_outcome`) and the familiar forms' place in the `given`
1604 group (`_text_outcomes`) stay in their helpers.
1606 - `group`: the `same_as` group its listed spellings are read in, the
1607 readings of the kind that stands there (`Lexicon._headwords`), so
1608 a given name's spelling never matches a surname (`Ma.` / `María`
1609 agree as given names; the surname Ma never matches María).
1610 - `compare`: the comparator where both sides hold the role, or, where
1611 `empty` is `None`, always: it then reads the two names whole (the
1612 suffix, which compares generations).
1613 - `empty`: the outcomes where neither side holds the role and where
1614 one side alone does; the family role's are both `conflict`, a
1615 family name being the minimum evidence.
1616 - `across`: the roles of the other name a cross-role match tries it
1617 against (`across-roles`), empty where it is never tried; the keys
1618 follow it.
1619 - `tried_into`: whether another reading may move words into it; a
1620 title never conflicts and a suffix only on its generation, so a
1621 word moved there could only empty a role that does."""
1623 group: str
1624 compare: _Compare
1625 empty: tuple[Outcome, Outcome] | None
1626 across: tuple[Role, ...] = ()
1627 tried_into: bool = True
1629 __getstate__ = _guarded_getstate
1630 __setstate__ = _guarded_setstate
1633def _compare_text(a: str, b: str, left: ParsedName, right: ParsedName,
1634 lexicon: Lexicon, accept: frozenset[Outcome],
1635 rule: _RoleRule) -> Outcome:
1636 """Two non-empty texts by `_text_outcome`."""
1637 return _text_outcome(a, b, lexicon, rule.group, accept)
1640def _compare_family(a: str, b: str, left: ParsedName, right: ParsedName,
1641 lexicon: Lexicon, accept: frozenset[Outcome],
1642 rule: _RoleRule) -> Outcome:
1643 """Two non-empty family names by `_text_outcome`, with the two family
1644 bases its leniencies compare (`particles-aside`, `part-of-other`)."""
1645 return _text_outcome(a, b, lexicon, rule.group, accept,
1646 (left.family_base, right.family_base))
1649def _compare_maiden(a: str, b: str, left: ParsedName, right: ParsedName,
1650 lexicon: Lexicon, accept: frozenset[Outcome],
1651 rule: _RoleRule) -> Outcome:
1652 """Two non-empty maiden names by `_text_outcome`, with the two maiden
1653 bases, particles set aside as `family_base` sets the family's, which
1654 the leniencies that read bases compare (`particles-aside`,
1655 `part-of-other`), outside the family chain (`chain=False`)."""
1656 return _text_outcome(a, b, lexicon, rule.group, accept,
1657 (_base_of(left, Role.MAIDEN),
1658 _base_of(right, Role.MAIDEN)), chain=False)
1661def _compare_middle(a: str, b: str, left: ParsedName, right: ParsedName,
1662 lexicon: Lexicon, accept: frozenset[Outcome],
1663 rule: _RoleRule) -> Outcome:
1664 return _middle_outcome(a, b, lexicon, accept, rule.group)
1667def _compare_noted(a: str, b: str, left: ParsedName, right: ParsedName,
1668 lexicon: Lexicon, accept: frozenset[Outcome],
1669 rule: _RoleRule) -> Outcome:
1670 return _noted(a, b, lexicon, rule.group, accept)
1673def _compare_suffix(a: str, b: str, left: ParsedName, right: ParsedName,
1674 lexicon: Lexicon, accept: frozenset[Outcome],
1675 rule: _RoleRule) -> Outcome:
1676 return _suffix_outcome(left, right, lexicon, rule.group, accept)
1679_EMPTY = (Outcome.SAME, Outcome.ONE_SIDE)
1681#: Each role's rule (`_RoleRule`), one row per `Role`.
1682_RULES: Mapping[Role, _RoleRule] = {
1683 Role.TITLE: _RoleRule("title", _compare_noted,
1684 (Outcome.SAME, Outcome.NOTED), tried_into=False),
1685 Role.GIVEN: _RoleRule("given", _compare_text,
1686 (Outcome.SAME, Outcome.GIVEN_ONE_SIDE),
1687 across=(Role.MIDDLE, Role.NICKNAME)),
1688 Role.MIDDLE: _RoleRule("given", _compare_middle, _EMPTY),
1689 Role.FAMILY: _RoleRule("family", _compare_family,
1690 (Outcome.CONFLICT, Outcome.CONFLICT),
1691 across=(Role.MAIDEN,)),
1692 Role.SUFFIX: _RoleRule("suffix", _compare_suffix, None, tried_into=False),
1693 Role.NICKNAME: _RoleRule("given", _compare_text, _EMPTY),
1694 Role.MAIDEN: _RoleRule("family", _compare_maiden, _EMPTY),
1695}
1698def _role_outcome(rule: _RoleRule, a: str, b: str, left: ParsedName,
1699 right: ParsedName, lexicon: Lexicon,
1700 accept: frozenset[Outcome]) -> Outcome:
1701 """Two texts of one role, `a` from `left` and `b` from `right`, by
1702 the role's rule: its comparator where both hold text or where it
1703 reads the names whole, else its outcome for one side or none."""
1704 if rule.empty is None or (a and b):
1705 return rule.compare(a, b, left, right, lexicon, accept, rule)
1706 both_empty, one_side = rule.empty
1707 return one_side if a or b else both_empty
1710def _compare_role(role: Role, left: ParsedName, right: ParsedName,
1711 lexicon: Lexicon, accept: frozenset[Outcome]) -> RoleMatch:
1712 """One role's `RoleMatch`, decided by its `_RULES` entry."""
1713 a, b = _role_text(left, role), _role_text(right, role)
1714 outcome = _role_outcome(_RULES[role], a, b, left, right, lexicon, accept)
1715 more = _row_more(outcome, a, b)
1716 # the table shows each field as written; `_role_text` is the reading
1717 return RoleMatch(role, outcome, getattr(left, role), getattr(right, role),
1718 more)