Skip to content

Commit 02071bc

Browse files
derek73claude
andcommitted
Address the review of #1533: unrecorded figures kept, messages per owner
- The three measurements no decisions entry holds yet (group's M1 bisect, _extract._overlaps, _vocab's script sweeps) stay in their comments until part C moves them; the pointers had read as though decisions/parse-cost held them. - A SettingEvidence row that is no triple, and a by_signal that is no iterable, are offered a row whose signal votes on the evidence's own setting (`_ROW_EXAMPLE`), not always a name_order row, which the two_family_names and patronymic_rules settings refuse. - One article helper (`_lexicon._a`) for every "a {kind}" message, with honorific's silent h; the completed_by=None clause says it leaves no listed word completing the word, which completes_any can still join. - Docstrings: surname1's family-comma example is under two_family_names; the nickname's alias marker is a listed one, @ and urf by default; ReadingSource.SHAPE's mixed-case word stands in a mixed-case name; Parser.suggest's two-family vote points at where it is weighed; suggest_measure's opening names every switch it suggests. - Tests: the vote test runs over every signal not voting on the order, a new test runs every setting's offered row, the article is checked per kind, the completed_by clearing is read in a parse with its shipped list asserted first, and the bare-string test round-trips. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 624e80b commit 02071bc

10 files changed

Lines changed: 119 additions & 38 deletions

File tree

‎nameparser/_lexicon.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@
9595
_NON_ASCII_EDGES = FULL_STOPS + _EDGE_JOINERS
9696

9797

98+
def _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+
98104
def _normalize(word: str) -> str:
99105
"""Lowercase, NFC-compose, strip whitespace and EDGE full stops
100106
(FULL_STOPS, not the ASCII period alone -- #322), and in a non-ASCII
@@ -1059,7 +1065,7 @@ def _prop_value(kind: str, prop: str, value: object) -> object:
10591065
# refuses it too (#1072)
10601066
cleared = ("joins it behind any plain word"
10611067
if prop == "completes"
1062-
else "leaves the word no phrase it completes")
1068+
else "leaves no listed word completing it")
10631069
raise ValueError(f"{prop} must list at least one word, got "
10641070
f"{value!r}; list the words it pairs with, or "
10651071
f"write {prop}=None to clear the list, which "
@@ -1200,7 +1206,7 @@ def _edit_props(kind: str, props: Mapping[str, object]) -> _Props:
12001206
"write add(word, kind='given', after_particle=True)")
12011207
if prop not in allowed:
12021208
raise ValueError(
1203-
f"{'an' if kind[:1] in 'aeiou' else 'a'} {kind} reading takes "
1209+
f"{_a(kind)} {kind} reading takes "
12041210
+ (", ".join(sorted(allowed)) or "no properties")
12051211
+ f"; got {prop!r}")
12061212
out[prop] = _prop_value(kind, prop, value)
@@ -1786,7 +1792,7 @@ def _check_base(base: object) -> object:
17861792
if name not in ri.indexed(kind):
17871793
raise ValueError(
17881794
f"a Lexicon snapshot gives {word!r}'s {kind} reading "
1789-
f"the property {name!r}, which a {kind} reading "
1795+
f"the property {name!r}, which {_a(kind)} {kind} reading "
17901796
f"does not take in this release")
17911797
try:
17921798
hash(value)
@@ -2010,7 +2016,7 @@ def __post_init__(self) -> None:
20102016
f"kinds are {', '.join(ri.CATEGORY)}")
20112017
if self.category != ri.CATEGORY[self.kind]:
20122018
raise ValueError(
2013-
f"a {self.kind} reading's category is "
2019+
f"{_a(self.kind)} {self.kind} reading's category is "
20142020
f"{ri.CATEGORY[self.kind]!r}, got {self.category!r}")
20152021
for name in ("properties", "languages"):
20162022
if not isinstance(getattr(self, name), tuple):

‎nameparser/_parser.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ def suggest(self, names: Iterable[str]) -> Suggestion:
315315
reads the group. ``names`` is any iterable of str the caller
316316
declares to be one group (one source, one convention), read
317317
once. Each name casts votes on its name order, its patronymic
318-
shape and, where the switch would change it,
318+
shape and, where the switch is weighed (below),
319319
``two_family_names``, read with this parser's lexicon past the
320320
titles it lists at the head and the post-nominals at the end; a
321321
name of fewer than two words once those are read past casts

‎nameparser/_pipeline/_extract.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,9 @@ def _overlaps(span: Span, taken: list[Span], starts: list[int]) -> bool:
214214
"""`taken` sorted and non-overlapping (both hold by construction),
215215
`starts` its start offsets. Bisect rather than scan: the closer
216216
sweep tests one span per delimiter character found, so a linear
217-
probe is quadratic in the number of matched pairs
218-
(decisions/parse-cost). Same idiom, and the same reason, as the
219-
origin resolution in _tokenize."""
217+
probe is quadratic in the number of matched pairs (400 pairs spent
218+
5.4ms here, against 2.5ms before the sweep existed). Same idiom, and
219+
the same reason, as the origin resolution in _tokenize."""
220220
i = bisect.bisect_right(starts, span.start) - 1
221221
# the only candidates are the last span starting at or before us and
222222
# its successor -- anything earlier ends before it, anything later

‎nameparser/_pipeline/_group.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1989,11 +1989,17 @@ def group(state: ParseState) -> ParseState:
19891989
# invariant, and script_segment only ever splits a token into
19901990
# sub-slices, so containment stays exact.
19911991
#
1992-
# Bisect rather than scan the token list per clause, which is
1993-
# quadratic in the number of delimited pairs (decisions/parse-cost);
1994-
# the same idiom, and the same reason, as _extract._overlaps and
1995-
# _tokenize's origin resolution. test_benchmark's maiden_pairs shape
1996-
# is the guard.
1992+
# Bisect rather than scan the token list per clause: that is
1993+
# quadratic in the number of delimited pairs, and "(a) " * 3200 --
1994+
# 4x test_benchmark's base, NOT a doubling -- measured a 14.1x cost
1995+
# against the 4.1x the same shape holds under a policy with no
1996+
# maiden_delimiters. The control is what says which unit a ratio is
1997+
# in: linear is ~4 for 4x the input and ~2 for a doubling, so a 4.1x
1998+
# control cannot be per doubling. Re-measured 2026-08-03 at 11.2x
1999+
# against 4.2x (3.2x against 2.1x per doubling) -- the separation
2000+
# replicates, the exact ratio moves with the runner. Same idiom,
2001+
# and the same reason, as _extract._overlaps and _tokenize's origin
2002+
# resolution. test_benchmark's maiden_pairs shape is the guard.
19972003
# rules/N4: "the marker dropped as M3 drops it" -- a nickname
19982004
# clause opening with an alias marker, by the same walk (decisions/N4 (#1164)).
19992005
# A plain loop over a map of a C getter, no frame: a name with no

‎nameparser/_pipeline/_vocab.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,12 @@
104104

105105
# The codepoint table lives in _policy beside Script -- one copy
106106
# importable from the pipeline and the locale packs alike; everything
107-
# here DERIVES from it. Each sweep is a compiled regex rather than a
108-
# per-character range test, as tokenize's separator scan is
109-
# (decisions/parse-cost).
107+
# here DERIVES from it. (single_script's sweep was first written
108+
# per-char on the _EMOJI_RANGES precedent in _tokenize.py, on the
109+
# theory that a range test needs no regex; measured at token scale the
110+
# compiled regex wins by 3-9x, and by roughly 70x on long tokens. The
111+
# precedent has since gone the same way: tokenize scans for its
112+
# separators with a compiled class, #1436.)
110113
# Derived, never hand-written -- even the class construction goes
111114
# through the shared factory: one wholly-of predicate per script, in
112115
# the table's key order -- the FIRST-covering-entry rule _classify

‎nameparser/_suggest.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,15 @@ def _iterable(value: object, owner: str, form: str, example: str
665665
return tuple(value)
666666

667667

668+
#: A ``by_signal`` row each setting takes, which a refused row's message
669+
#: offers: one whose signal votes on that setting
670+
_ROW_EXAMPLE: Mapping[str, str] = MappingProxyType({
671+
_NAME_ORDER: "(Signal.SURNAME, FAMILY_FIRST, 2)",
672+
_PATRONYMIC_RULES: "(Signal.PATRONYMIC, PatronymicRule.EAST_SLAVIC, 2)",
673+
_TWO_FAMILY_NAMES: "(Signal.FIRST_SURNAME, True, 2)",
674+
})
675+
676+
668677
def _checked_row(row: object, setting: str) -> tuple[Signal, Vote, int]:
669678
"""One ``by_signal`` row, validated: ``(signal, vote, count)``, its
670679
signal one that votes on ``setting``."""
@@ -673,7 +682,7 @@ def _checked_row(row: object, setting: str) -> tuple[Signal, Vote, int]:
673682
raise TypeError(
674683
f"SettingEvidence by_signal rows must be (signal, vote, count) "
675684
f"triples, got {reprlib.repr(row)}; pass e.g. "
676-
f"(Signal.SURNAME, FAMILY_FIRST, 2)")
685+
f"{_ROW_EXAMPLE.get(setting, _ROW_EXAMPLE[_NAME_ORDER])}")
677686
signal, vote, count = row
678687
pair = _checked_vote(signal, vote, "SettingEvidence by_signal")
679688
if _SETTING_OF[pair[0]] != setting:
@@ -865,7 +874,8 @@ def __post_init__(self) -> None:
865874
f"pass '' for no note")
866875
rows = _iterable(self.by_signal, "SettingEvidence by_signal",
867876
"an iterable of (signal, vote, count) rows",
868-
"((Signal.SURNAME, FAMILY_FIRST, 2),) or ()")
877+
f"({_ROW_EXAMPLE.get(self.setting, _ROW_EXAMPLE[_NAME_ORDER])},)"
878+
" or ()")
869879
object.__setattr__(
870880
self, "by_signal",
871881
tuple(_checked_row(row, self.setting) for row in rows))

‎nameparser/_types.py‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -970,8 +970,8 @@ class ReadingSource(StrEnum):
970970
DECLARED = "declared"
971971
#: The word's shape, not a list: a roman numeral, letters run
972972
#: together with periods ("X.Y.Z."), a word in capitals, or after a
973-
#: comma a word in mixed case that opens with two capitals or ends in
974-
#: one ("MRes").
973+
#: comma, in a name written in mixed case, a word that opens with two
974+
#: capitals or ends in one ("MRes").
975975
SHAPE = "shape"
976976
#: Nothing lists or shapes the word into this reading; it is the
977977
#: reading any word has where it stands, an ordinary name word. A
@@ -1492,9 +1492,10 @@ def nickname(self) -> str:
14921492
"""The words written inside nickname delimiters (quotes,
14931493
parentheses; :attr:`Policy.nickname_delimiters
14941494
<nameparser.Policy.nickname_delimiters>`), the delimiters
1495-
dropped, and the words after an alias marker (``@`` or ``urf``
1496-
written as a word of its own: ``Ali @ Abu bin Ahmad`` gives
1497-
``Abu``), the marker dropped, space-joined in written order;
1495+
dropped, and the words after a listed alias marker (by default
1496+
``@`` or ``urf`` written as a word of its own: ``Ali @ Abu bin
1497+
Ahmad`` gives ``Abu``), the marker dropped, space-joined in
1498+
written order;
14981499
``''`` for a name with none."""
14991500
return self._text_for(Role.NICKNAME)
15001501

@@ -1642,9 +1643,9 @@ def _first_unit(self) -> bool:
16421643
@property
16431644
def surname1(self) -> str:
16441645
"""The family's first name unit where the parse read the family
1645-
as two (``García`` in ``Gabriel García Márquez`` under
1646-
``two_family_names``, and in ``García Márquez, Gabriel``, ``de
1647-
la Vega`` in ``Juan de la Vega del Valle`` under it too, ``王``
1646+
as two (``García`` in ``Gabriel García Márquez`` and in ``García
1647+
Márquez, Gabriel`` under ``two_family_names``, ``de la Vega`` in
1648+
``Juan de la Vega del Valle`` under it too, ``王``
16481649
in ``王李小明`` under ``locales.ZH``), :attr:`surname2` being the
16491650
other;
16501651
elsewhere the whole :attr:`family`. A middle name

‎tests/v2/test_lexicon.py‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2231,16 +2231,37 @@ def test_a_pair_list_given_a_bare_string_offers_a_list_that_runs(
22312231
added = Lexicon.default().add("zzend", kind=kind,
22322232
**{prop: eval(offered)})
22332233
assert [dict(r.properties)[prop] for r in added.readings_of("zzend")] == [
2234-
(word,)]
2234+
tuple(sorted(eval(offered)))]
22352235

22362236

22372237
def test_completed_by_none_clears_the_list_the_message_offers_to_clear() -> None:
22382238
# the empty-list refusal offers `completed_by=None` to clear a list
2239-
# the word's reading has; run it on a word that ships one
2240-
with pytest.raises(ValueError, match="completed_by=None"):
2239+
# the word's reading has; run what it offers on a word that ships
2240+
# one, and read the clearing in a parse (rules/P12)
2241+
with pytest.raises(ValueError, match="completed_by=None") as refused:
22412242
Lexicon.default().add("عبد", kind="bound_given", completed_by=[])
2243+
offered = str(refused.value).split("write ", 1)[1].split(" to clear")[0]
2244+
assert offered == "completed_by=None"
2245+
shipped = [dict(r.properties) for r in
2246+
Lexicon.default().readings_of("عبد")
2247+
if r.kind == "bound_given"]
2248+
assert shipped and all(p.get("completed_by") for p in shipped)
2249+
assert Parser().parse("سامر نور عبد الله").family == "عبد الله"
22422250
cleared = Lexicon.default().add("عبد", kind="bound_given",
22432251
completed_by=None)
2244-
assert all("completed_by" not in dict(r.properties)
2245-
or dict(r.properties)["completed_by"] is None
2246-
for r in cleared.readings_of("عبد"))
2252+
assert [(r.kind, r.properties) for r in cleared.readings_of("عبد")] == [
2253+
("bound_given", ())]
2254+
assert Parser(lexicon=cleared).parse("سامر نور عبد الله").family == "الله"
2255+
2256+
2257+
@pytest.mark.parametrize("kind, article", [
2258+
("academic", "an"), ("alias_marker", "an"), ("article", "an"),
2259+
("honorific", "an"), ("occupation", "an"), ("title", "a"),
2260+
("nobility", "a"), ("given", "a")])
2261+
def test_a_refused_property_names_the_kind_with_its_article(
2262+
kind: str, article: str) -> None:
2263+
# every kind beginning with a vowel, and honorific, whose h is
2264+
# silent, reads "an"; the rest "a"
2265+
with pytest.raises(ValueError,
2266+
match=f"^{article} {kind} reading takes "):
2267+
Lexicon.empty().add("zzq", kind=kind, zzprop=True) # type: ignore[call-arg]

‎tests/v2/test_suggest.py‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3684,11 +3684,21 @@ def test_a_switch_not_weighed_says_why_and_casts_no_vote(
36843684
assert not any(Signal.FIRST_SURNAME in name.votes for name in s.names)
36853685

36863686

3687-
@pytest.mark.parametrize("signal, bad, setting, value", [
3688-
(Signal.FIRST_SURNAME, 1, "two_family_names", True),
3689-
(Signal.PATRONYMIC, "east-slavic", "patronymic_rules",
3690-
frozenset({PatronymicRule.EAST_SLAVIC})),
3691-
])
3687+
#: A value of each setting a signal votes on, for SettingEvidence rows
3688+
_SETTING_VALUES: dict[str, object] = {
3689+
"name_order": FAMILY_FIRST, "two_family_names": True,
3690+
"patronymic_rules": frozenset({PatronymicRule.EAST_SLAVIC})}
3691+
3692+
3693+
def _non_order_signals() -> list[tuple[Signal, object, str, object]]:
3694+
from nameparser._suggest import _SETTING_OF
3695+
bad = {"two_family_names": 1, "patronymic_rules": "east-slavic"}
3696+
return [(signal, bad[setting], setting, _SETTING_VALUES[setting])
3697+
for signal, setting in _SETTING_OF.items()
3698+
if setting != "name_order"]
3699+
3700+
3701+
@pytest.mark.parametrize("signal, bad, setting, value", _non_order_signals())
36923702
def test_a_refused_vote_offers_its_owners_shape_and_the_code_runs(
36933703
signal: Signal, bad: object, setting: str, value: object) -> None:
36943704
# a NameEvidence vote is a mapping entry, a SettingEvidence row a
@@ -3706,3 +3716,26 @@ def test_a_refused_vote_offers_its_owners_shape_and_the_code_runs(
37063716
row = eval(str(row_refused.value).rsplit("pass e.g. ", 1)[1], names)
37073717
SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type]
37083718
(row,))
3719+
3720+
3721+
3722+
def _settings_voted_on() -> list[str]:
3723+
from nameparser._suggest import _SETTING_OF
3724+
return sorted(set(_SETTING_OF.values()))
3725+
3726+
3727+
@pytest.mark.parametrize("setting", _settings_voted_on())
3728+
def test_a_row_that_is_no_triple_is_offered_a_row_of_its_own_setting(
3729+
setting: str) -> None:
3730+
# every setting a signal votes on is offered a row whose signal
3731+
# votes on it (the name_order row was offered for every setting
3732+
# until the 3.2 prose sweep), and the offered row is accepted
3733+
value = _SETTING_VALUES[setting]
3734+
names = {"Signal": Signal, "PatronymicRule": PatronymicRule,
3735+
"FAMILY_FIRST": FAMILY_FIRST}
3736+
with pytest.raises(TypeError) as refused:
3737+
SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type]
3738+
("x",)) # type: ignore[arg-type]
3739+
row = eval(str(refused.value).rsplit("pass e.g. ", 1)[1], names)
3740+
SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type]
3741+
(row,))

‎tools/differential/suggest_measure.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""Measure Parser.suggest on groups of names whose written order is known.
22
33
`Parser.suggest(names)` reads a group of names a caller declares to share
4-
one convention and suggests a `name_order` (and `patronymic_rules`). Its
4+
one convention and suggests a `name_order` (and `patronymic_rules`,
5+
`initials_as_family`, `capitals_as_family` and `two_family_names`). Its
56
decision rule (`_suggest._MIN_VOTES`, `_MIN_SHARE`,
67
`_MIN_ORDER_GROUP_SHARE`, `_MIN_PATRONYMIC_SHARE`, `_MIN_PATRONYMIC_VOTES`, the trailing-initial
78
signal's `_MIN_TRAILING_NAMES` and `_MIN_TRAILING_SHARE`, and for

0 commit comments

Comments
 (0)