From a54f0892d20da3c6c44b3e42be29f483ad6f7495 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:19:40 -0800 Subject: [PATCH 1/7] Warn when Lexicon.remove names a reading no vocabulary file holds (#1535) remove(word, kind=...) of a kind the word does not hold, or of a word in no file, took nothing and said nothing: docs/migrate.rst's alhaj recipe shipped that way, its doctest passing without the edit. remove() now emits a UserWarning for each such word, naming the kinds it does hold and offering the remove that would take one. A reading counts if any file holds it, on by default or not (a choice may turn it on), or if an earlier add() of the same lexicon gave it; a category counts where any of its kinds is held. The warning is raised at the caller's own line through _warn_at_caller, in remove() alone, so a lexicon replaying its log (dataclasses.replace, a pickle load) never warns again. remove of every word's readings and the familiar and spelling pair removes are not judged. Three tests removed a reading on purpose that the warning now names, and assert it: a remove before the add it would undo, a no-kind remove of a name held only as another word's pair, and a pack fragment removing a reading another fragment adds, which remove() cannot see. Co-Authored-By: Claude Opus 5.5 --- nameparser/_lexicon.py | 47 +++++++++++++ tests/v2/test_lexicon.py | 143 ++++++++++++++++++++++++++++++++++++++- tests/v2/test_match.py | 5 +- tests/v2/test_parser.py | 7 +- 4 files changed, 198 insertions(+), 4 deletions(-) diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 2793c2f16..eba30d672 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2627,10 +2627,57 @@ def remove(self, *words: str, kind: str | None = None, "word's readings of it, e.g. remove(kind='title', " "every=True)") edit = _make_edit("remove", words, kind, pairs) + for message in self._inert_removes(edit): + _warn_at_caller(message) return dataclasses.replace(self, _edits=self._edits + (edit,)) # -- private helpers -------------------------------------------------- + def _inert_removes(self, edit: _Edit) -> list[str]: + """A warning for each word of a `remove` that no vocabulary file + and no earlier `add` of this lexicon gives a reading of the kind + asked (any reading, with no kind), so that the edit can take + effect under no choice of languages (#1535). A file's reading + counts whether it is on by default or not, since a choice may + turn it on. Read at `remove` alone, never when a constructor + replays the log or a pickle loads. A remove of every word's + readings (no words) and the familiar and spelling pair removes, + which match names by their folded forms, are not judged.""" + ri = _index_module() + kind = edit.kind + if not edit.words or (kind is not None and ri.CATEGORY.get( + kind, kind) in ri.MATCHING_ONLY): + return [] + added: dict[str, set[str]] = {} + for earlier in self._edits: + if earlier.op == "add" and earlier.kind is not None: + for w in earlier.words: + added.setdefault(w, set()).add(earlier.kind) + messages = [] + for w in edit.words: + held = {r.kind for r in ri.readings_of(w)} | added.get(w, set()) + if kind is None: + if not held: + messages.append( + f"remove({w!r}) changes nothing: {w!r} is in no " + f"vocabulary file and no earlier add() of this " + f"lexicon; check its spelling") + continue + if any(k == kind or ri.CATEGORY[k] == kind for k in held): + continue + if not held: + messages.append( + f"remove({w!r}, kind={kind!r}) changes nothing: {w!r} " + f"is in no vocabulary file and no earlier add() of " + f"this lexicon; check its spelling") + continue + kinds = sorted(held) + messages.append( + f"{w!r} has no {kind!r} reading in any vocabulary file; " + f"its readings are: {', '.join(kinds)}. Did you mean " + f"remove({w!r}, kind={kinds[0]!r})?") + return messages + def _pool(self) -> Pool: return self._files.pool() diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 5f1e194fa..aff05f6a9 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -1407,7 +1407,10 @@ def test_two_lexicons_are_equal_when_their_logs_are_as_written() -> None: def test_a_later_edit_reads_after_an_earlier_one() -> None: lex = Lexicon.empty() assert lex.add("x", kind="title").remove("x")._sets.titles == frozenset() - assert lex.remove("x").add("x", kind="title")._sets.titles == {"x"} + # a remove before the add it would undo takes nothing, and warns (#1535) + with pytest.warns(UserWarning, match="'x' is in no vocabulary file"): + removed_first = lex.remove("x") + assert removed_first.add("x", kind="title")._sets.titles == {"x"} def test_replace_carries_the_base_and_the_log() -> None: @@ -2217,3 +2220,141 @@ def test_words_finds_a_spelling_of_several_by_any_word_it_names() -> None: assert "md" not in lexicon.words(kind="given", same_as=["muhammad", "mohamad"]) assert lexicon.words(kind="given", same_as="charles") == ("chas",) + + +# -- a remove that takes nothing (#1535) ------------------------------------ +# +# remove() warns where no vocabulary file and no earlier add() of the +# lexicon gives the word a reading of the kind asked, since such an edit +# takes effect under no choice of languages. + +_INERT_REMOVES = [ + # a kind the word does not hold: the warning names the kinds it does + pytest.param(lambda L: L.remove("alhaj", kind="religious"), + ["'alhaj' has no 'religious' reading", "style", + "remove('alhaj', kind='style')"], id="wrong-kind"), + # a word in no file, with a kind and without one + pytest.param(lambda L: L.remove("zzyzx", kind="title"), + ["remove('zzyzx', kind='title') changes nothing", + "in no vocabulary file"], id="unknown-word"), + pytest.param(lambda L: L.remove("zzyzx"), + ["remove('zzyzx') changes nothing", + "in no vocabulary file"], id="unknown-word-no-kind"), + # a category none of whose kinds the word holds + pytest.param(lambda L: L.remove("alhaj", kind="name"), + ["'alhaj' has no 'name' reading", + "remove('alhaj', kind='style')"], id="category-none-held"), +] + + +@pytest.mark.parametrize("call, expected", _INERT_REMOVES) +def test_a_remove_that_takes_nothing_warns( + call: Callable[[Lexicon], Lexicon], expected: list[str]) -> None: + with pytest.warns(UserWarning) as record: + removed = call(Lexicon.default()) + assert len(record) == 1 + message = str(record[0].message) + for part in expected: + assert part in message, message + # the edit is still logged, as before + assert len(removed._edits) == 1 + + +def test_a_remove_of_several_words_names_only_those_it_takes_nothing_from() -> None: + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("alhaj", "qari", "zzyzx", kind="religious") + messages = [str(w.message) for w in record] + assert len(messages) == 2 + assert any("'alhaj'" in m for m in messages) + assert any("'zzyzx'" in m for m in messages) + assert not any("'qari'" in m for m in messages) + + +def test_the_remove_a_warning_offers_takes_the_reading() -> None: + # the offered call is code to paste: run it, on the default, and + # check that it takes the reading the inert one missed + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("alhaj", kind="religious") + offered = re.search(r"remove\([^)]*\)", str(record[0].message)) + assert offered is not None + fixed = eval("Lexicon.default()." + offered.group(0)) # noqa: S307 + assert "style" in {r.kind for r in Lexicon.default().readings_of("alhaj")} + assert "style" not in {r.kind for r in fixed.readings_of("alhaj")} + assert Parser(lexicon=fixed).parse("Alhaj Ahmed Khan").title == "" + + +@pytest.mark.parametrize("call", [ + # a reading a file holds off by default, which a choice turns on + pytest.param(lambda L: L.remove("piedade", kind="given"), + id="default-false"), + # a category one of whose kinds the word holds + pytest.param(lambda L: L.remove("dean", kind="title"), id="category"), + # the lexicon's own earlier add, and a second remove of a reading + pytest.param(lambda L: L.add("zzorvan", kind="family") + .remove("zzorvan", kind="family"), id="own-add"), + pytest.param(lambda L: L.add("zzorvan", kind="family") + .remove("zzorvan", kind="family") + .remove("zzorvan", kind="family"), id="own-add-twice"), + pytest.param(lambda L: L.remove("phd", kind="credential") + .remove("phd", kind="credential"), id="file-twice"), + # a remove of every word's readings of a kind names no word + pytest.param(lambda L: L.remove(kind="title", every=True), id="every"), + # the pair removes are judged by name matching's folded forms + pytest.param(lambda L: L.remove("zzbob", kind="familiar"), + id="familiar"), + pytest.param(lambda L: L.remove("zzsara", kind="spelling", + spelling_of=["zzsarah"]), + id="spelling"), +]) +def test_a_remove_that_can_take_effect_is_silent( + call: Callable[[Lexicon], Lexicon]) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error") + call(Lexicon.default()) + + +def test_a_remove_warning_points_at_the_callers_line() -> None: + def line_of(make: Callable[[], object]) -> tuple[str, int]: + with pytest.warns(UserWarning) as record: + make() + return record[0].filename, record[0].lineno + + def plain() -> object: + return Lexicon.default().remove("zzyzx") + + def chained() -> object: + return Lexicon.default().remove("dean", kind="title").remove("zzyzx") + + def in_a_parser() -> object: + return Parser(lexicon=Lexicon.default().remove("zzyzx")) + + for make in (plain, chained, in_a_parser): + filename, lineno = line_of(make) + # the warning names this file and the remove's own line, the + # function's body, not a line inside the library + assert filename == __file__ + assert lineno == make.__code__.co_firstlineno + 1, make.__name__ + + +def test_a_logged_remove_does_not_warn_again() -> None: + with pytest.warns(UserWarning): + inert = Lexicon.default().remove("zzyzx", kind="title") + with warnings.catch_warnings(): + warnings.simplefilter("error") + # replaying the log, by a copy and by a pickle, warns nothing + dataclasses.replace(inert, given_names=frozenset({"luis"})) + loaded = pickle.loads(pickle.dumps(inert)) + assert loaded == inert + Parser(lexicon=inert).parse("Zzyzx Smith") + + +def test_every_pack_builds_with_no_remove_warning() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings( + "ignore", message="Policy.segment_scripts activates") + for code in locales.available(): + pack = locales.get(code) + parser_for(pack) + if pack.languages: + parser_for(pack, strict=True) diff --git a/tests/v2/test_match.py b/tests/v2/test_match.py index d9487f5dd..35c550feb 100644 --- a/tests/v2/test_match.py +++ b/tests/v2/test_match.py @@ -2803,7 +2803,10 @@ def test_a_remove_of_every_reading_of_a_word_keeps_the_pairs_other_words_hold() # spelling ones among them; a pair another word holds with it is # that word's reading, and takes a remove of the kind (#1404) lexicon = _pairs("familiar", "short_for").add("zzbo", kind="title") - after = lexicon.remove("zzbo").remove("zzrobert") + # zzrobert holds no reading of its own, so the remove takes nothing + # and warns (#1535) + with pytest.warns(UserWarning, match="'zzrobert' is in no vocabulary"): + after = lexicon.remove("zzbo").remove("zzrobert") assert after.readings_of("zzbo") == () assert after._familiar_forms("zzrobert") == {"zzrob"} diff --git a/tests/v2/test_parser.py b/tests/v2/test_parser.py index d56620a34..18dfec736 100644 --- a/tests/v2/test_parser.py +++ b/tests/v2/test_parser.py @@ -3263,8 +3263,11 @@ def test_a_packs_fragment_joins_under_the_callers_lexicon() -> None: # and a later pack's fragment after an earlier one's first = _choosing("en", code="aa", lexicon=Lexicon.empty().add("zzq", kind="title")) - second = _choosing("en", code="bb", - lexicon=Lexicon.empty().remove("zzq", kind="title")) + # the fragment's remove takes out a reading another lexicon adds, which + # remove() cannot see, so it warns that no file holds it (#1535) + with pytest.warns(UserWarning, match="'zzq' is in no vocabulary file"): + second = _choosing("en", code="bb", + lexicon=Lexicon.empty().remove("zzq", kind="title")) assert parser_for(first, second).parse("Zzq Smith").title == "" assert parser_for(second, first).parse("Zzq Smith").title == "Zzq" From 600284c24230b9f7ebad60d2b85f533be1451296 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:25:18 -0800 Subject: [PATCH 2/7] Document the remove warning: docstring, customize.rst, release log, decisions, AGENTS.md (#1535) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/customize.rst | 22 ++++++++++++++++++++++ docs/design/decisions/vocabulary-model.md | 2 ++ docs/release_log.rst | 1 + nameparser/_lexicon.py | 10 +++++++++- 5 files changed, 35 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6ed5df0e8..89f656efd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -296,7 +296,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 - **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; every locale pack module (`locales/*.py`) imports `_locale`/`_lexicon`/`_policy`/`_types` and its own private data modules, or its language pack's, in `locales/` only (`es.py` imports `_es_given_names.py`, `es_ar.py` `_es_ar_given_names.py`, and `pt_br.py` and `pt_pt.py` share `_pt_given_names.py`, #1453; `_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), a data module (a leading underscore) imports nothing internal, and the `locales/__init__` additionally lazy-imports its packs (PEP 562). No pack is keyed by hand: the test's `_locale_rules()` holds every file in `locales/` to that rule, a relative import read by the absolute name it resolves to, so a new pack is checked from its first commit. Extend the test's `ALLOWED` table when adding any other module; its completeness checks fail on a `_pipeline/` module it does not key and on a `locales/` module no rule reaches. - **Canonical field order** — the seven roles in `Role` enum declaration order, defined once and derived everywhere (properties, `as_dict`, reprs, `comparison_key`). Never restate the order literally. `Role` is a `StrEnum`: members compare as their field-name strings, and `tokens_for()` coerces strings via `_coerce_enum`. - **Method organization**, fixed section order in every class: fields + `__post_init__` validation → alternative constructors → dunders (construction/equality → protocol → operators) → properties → public methods by concern (access → editing → comparison → rendering delegates) → private helpers last, except a helper serving exactly one section may sit at that section's head. -- **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). +- **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A recipe's doctest can pass with its edit doing nothing**: an example that removes a reading and then shows a reading true with or without the removal proves nothing, and #1534's review found docs/migrate.rst removing `alhaj` as a religious title (it is a style), the doctest green throughout. Run each recipe's example without its edit too and check that the output moves; `Lexicon.remove` now warns where no file holds the reading named (#1535), which catches that shape, but not an edit that holds a reading the example never reaches. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). - **Guard, hint, and emit for the WHOLE family, and parametrize the test over it**: a check added to one member of a set belongs on all of it, and the test must sweep the family, not one example. This session shipped `_reject_str_and_mapping` on `Policy` but not `PolicyPatch`, the bytes decode hint on three of five config entry points, and a regex-sync roster missing four of its copies — each a separate follow-up bug that a `{class} × {field} × {bad-value}` parametrization would have caught and a per-example test hid. When you find you're guarding member N, grep for the other members first. - **Ambiguities are emitted at the DECISION site**: an `Ambiguity` records a fork the parse had to call, not a token that sits in an ambiguous vocabulary, so emit where the branch is taken, in every stage that takes one, and name the reading not taken. The reading TAKEN (`Token.reading`, 3.0) is the one read later, at assemble, where roles are final, from the role and the tags the deciding stages left, its suffix and name sources by the predicates that name the reading not taken. The contract is mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE; the working rules (branches that change nothing, the field a report names, the stages that decide `PARTICLE_OR_GIVEN`, `alternative`, the reading taken, and how to test an emitter) are in `nameparser/_pipeline/AGENTS.md`, which loads when a session reads a pipeline stage. - **A kind is worth adding only if a reader would hesitate too**: the test is not "does the code take a branch" but whether a person reading that input would genuinely be unsure. "Smith, John V." reads as a middle initial to anyone -- the period settles it -- so reporting it would be noise that teaches callers to ignore the field, which costs more than the missing report. Reachability of the second branch is necessary, not sufficient. The example was "Smith, John V" until #877 measured FEC writing that bare letter as a middle initial about as often as letter frequency predicts, where the parser reads the generation: a fork that feels settled is a claim to measure against the data before it decides a report. Prefer leaving a fork silent and documenting the omission over emitting on input nobody finds ambiguous. diff --git a/docs/customize.rst b/docs/customize.rst index da907e6bb..3fdc088b7 100644 --- a/docs/customize.rst +++ b/docs/customize.rst @@ -148,6 +148,28 @@ its category: >>> Parser(lexicon=lean).parse("Professor Robert Johns").title '' +A remove that can take nothing, a kind the word does not hold or a word +no vocabulary file lists, warns, naming the kinds the word does hold. +``alhaj`` is a style, not a religious title: + +.. doctest:: + + >>> import warnings + >>> with warnings.catch_warnings(record=True) as caught: + ... warnings.simplefilter("always") + ... inert = Lexicon.default().remove("alhaj", kind="religious") + >>> print(caught[0].message) + 'alhaj' has no 'religious' reading in any vocabulary file; its readings are: style. Did you mean remove('alhaj', kind='style')? + >>> Parser(lexicon=inert).parse("Alhaj Ahmed Khan").title + 'Alhaj' + +A reading some file holds counts even where it is off by default, since +a choice of languages may turn it on, and so does one the same lexicon +added earlier. A fragment meant to remove a reading another lexicon +adds when the two are joined cannot be checked that way; keep its +remove quiet with ``warnings.catch_warnings()`` and +``warnings.simplefilter("ignore", UserWarning)`` around the call. + Seeing what the vocabulary says about a word ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 43a64bd6f..2f6a47ca5 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -653,3 +653,5 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **Accepted:** under strict `ms`, a ruler's style opening a name reads the given name, as it does by default and under `locales.MS` (`Sultan Rahmat ibni Sultan Kamil` → given 'Sultan'); behind a style it stays the title where the style is read (`His Majesty Sultan Rahmat` under strict `ms` + `en`; strict `ms` alone drops en.toml's `his` and `majesty`, before this change and after). - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). + +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an earlier `add` in the same lexicon's log gave it; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. Where the word holds other kinds the message lists them and offers `remove(word, kind=)`, code a test runs and checks takes the reading; where it holds none, the message says it is in no vocabulary file and no earlier add, with no call to offer. One warning per inert word, the held words of the same call unnamed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED: a fragment whose remove targets a reading another lexicon adds when the two are joined warns, since the call cannot see that lexicon (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters the warning around the call. A word spelled in a way the fold does not reach warns as unknown, which is the intended signal. MEASURED: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move, `remove` not being on the parse path; no shipped pack, plain or strict, warns; in the repository's own tests three removes named readings nothing held, each a test exercising an inert remove on purpose, and none in docs/, README.rst or tools/. OPEN: whether an `add` of a reading the word already holds, with the same properties, deserves the same treatment; it is inert too, but the natural result of copying a recipe. diff --git a/docs/release_log.rst b/docs/release_log.rst index dc7c9f74d..11e1d88f1 100644 --- a/docs/release_log.rst +++ b/docs/release_log.rst @@ -46,6 +46,7 @@ Release Log - **Change locales.HR and locales.SL to read two family names, as locales.CS and locales.SK do.** ``parser_for(locales.HR).parse("Ana Puž Kukuljan")`` gives family ``Puž Kukuljan``, where 3.0.0 through 3.1.0 gave middle ``Puž``, family ``Kukuljan``; with no given-name list, a second given name is read as a family name too (``Janez Jože Novak`` gives family ``Jože Novak`` under ``locales.SL``), and a family comma keeps both as before. :issue:`1190` - **Change locales.PT_BR to read two family names, and add locales.PT_PT, which reads names from Portugal the same way.** ``parser_for(locales.PT_BR).parse("Ana Souza Lima")`` gives family ``Souza Lima``, where 3.0.0 through 3.1.0 gave middle ``Souza``, family ``Lima``; a second given name on the packs' Portuguese given-name list stays where it stands (``Ana Beatriz Costa`` keeps family ``Costa``), and ``locales.PT``, chosen for Portuguese names from any country, is unchanged. ``locales.PT_PT`` also reads four given names Portugal writes behind a particle and Brazil does not (``Maria do Rosário Pinto`` gives middle ``do Rosário``, as ``do Carmo``, ``da Conceição`` and ``da Luz`` do). :issue:`1453`, :issue:`1189` - **Change the Spanish given-name lists, rewritten from their tool.** ``parser_for(locales.ES_AR).parse("Juan Gerhard Lopez")`` gives family ``Gerhard Lopez``, where 3.0.0 through 3.1.0 gave middle ``Gerhard``; nine words leave locales.ES_AR's list (``Gerhard``, ``Zuleyma`` among them) and nine join it (``Azhar``, ``Houari``, ``Grace``), each joining reading as a middle name where it read as the first family name, and locales.ES's gains ``Lahcen`` and drops ``Rim``. :issue:`1471`, :issue:`1476` + - **Add a warning when Lexicon.remove names a reading no vocabulary file holds, which took nothing and said nothing.** ``Lexicon.default().remove("alhaj", kind="religious")`` now warns ``'alhaj' has no 'religious' reading in any vocabulary file; its readings are: style. Did you mean remove('alhaj', kind='style')?``, where 3.1.0 returned the lexicon unchanged in silence; a word in no file warns too, while a reading a choice of languages would turn on, or one the same lexicon added earlier, stays silent. A fragment that removes a reading another lexicon adds when the two are joined warns as well, since the call cannot see that lexicon. :issue:`1535` * 3.1.0 - November 16, 2026 diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index eba30d672..00f190f6c 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2578,7 +2578,15 @@ def remove(self, *words: str, kind: str | None = None, empty ``remove(*words, kind=...)`` never takes out a whole kind. Removing a reading the word does not hold changes nothing now, and is kept: a later choice of languages may turn that reading - on. + on. Where no vocabulary file holds the reading, on by default or + not, and no earlier :meth:`add` of this lexicon gave it, the + edit can never take effect, and the call warns with a + ``UserWarning`` naming the kinds the word does hold (#1535); a + remove of every word's readings and a ``familiar`` or + ``spelling`` pair remove are not judged. A fragment removing a + reading another lexicon adds when the two are joined warns too, + since this call cannot see that lexicon; filter the warning + around that call. A ``familiar`` or ``spelling`` reading is a pair of given names, stored on one of the two and read by name matching both ways, so From b277dbfa352d30b0c6823a17179e3f042580fb8b Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:27:22 -0800 Subject: [PATCH 3/7] Say which case a remove warning is, and offer the pair remove for a name held only in pairs (#1535) The message now tells three cases apart: a word in the vocabulary without that kind (its kinds and the call that takes one), a word in no file and no earlier add, and, with no kind, a word holding no reading of its own, only the other name of another word's familiar or spelling pair, for which it offers remove(word, kind="familiar") or "spelling", the call that reaches pairs; a test runs that call and checks the pair goes. The docstring, docs/customize.rst and the decisions entry state the accepted case in the issue's terms: a fragment meant to remove a word another lexicon adds warns, since remove cannot see the lexicon it will be joined with, and its caller filters that warning by its message, never by category, or removes on the joined lexicon; customize.rst's recipe shows the filter, with a title example whose output moves. Co-Authored-By: Claude Opus 5.5 --- docs/customize.rst | 19 +++++++++++---- docs/design/decisions/vocabulary-model.md | 2 +- nameparser/_lexicon.py | 29 +++++++++++++++++++---- tests/v2/test_match.py | 22 ++++++++++++++++- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/docs/customize.rst b/docs/customize.rst index ecb0c5361..cbd970257 100644 --- a/docs/customize.rst +++ b/docs/customize.rst @@ -186,10 +186,21 @@ no vocabulary file lists, warns, naming the kinds the word does hold. A reading some file holds counts even where it is off by default, since a choice of languages may turn it on, and so does one the same lexicon -added earlier. A fragment meant to remove a reading another lexicon -adds when the two are joined cannot be checked that way; keep its -remove quiet with ``warnings.catch_warnings()`` and -``warnings.simplefilter("ignore", UserWarning)`` around the call. +added earlier. A fragment meant to remove a word another lexicon adds +warns, since ``remove`` cannot see the lexicon it will be joined with. +Do the remove on the joined lexicon, or filter that one warning by its +message, never by its category, which would hide every other warning: + +.. doctest:: + + >>> with warnings.catch_warnings(): + ... warnings.filterwarnings("ignore", message=r"remove\('zzq'") + ... fragment = Lexicon.empty().remove("zzq", kind="title") + >>> with_zzq = Lexicon.default().add("zzq", kind="title") + >>> Parser(lexicon=with_zzq).parse("Zzq Ana Smith").title + 'Zzq' + >>> Parser(lexicon=with_zzq | fragment).parse("Zzq Ana Smith").title + '' Seeing what the vocabulary says about a word ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 2f6a47ca5..4861680dc 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -654,4 +654,4 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). -- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an earlier `add` in the same lexicon's log gave it; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. Where the word holds other kinds the message lists them and offers `remove(word, kind=)`, code a test runs and checks takes the reading; where it holds none, the message says it is in no vocabulary file and no earlier add, with no call to offer. One warning per inert word, the held words of the same call unnamed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED: a fragment whose remove targets a reading another lexicon adds when the two are joined warns, since the call cannot see that lexicon (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters the warning around the call. A word spelled in a way the fold does not reach warns as unknown, which is the intended signal. MEASURED: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move, `remove` not being on the parse path; no shipped pack, plain or strict, warns; in the repository's own tests three removes named readings nothing held, each a test exercising an inert remove on purpose, and none in docs/, README.rst or tools/. OPEN: whether an `add` of a reading the word already holds, with the same properties, deserves the same treatment; it is inert too, but the natural result of copying a recipe. +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an earlier `add` in the same lexicon's log gave it; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. The message says which of three cases it is: (i) the word is in the vocabulary but not in that kind, and the message lists its kinds and offers `remove(word, kind=)`; (ii) the word is in no vocabulary file and no earlier add of the lexicon, with no call to offer; (iii) a remove with no kind of a word holding no reading of its own, only the other name of another word's `familiar` or `spelling` pair, and the message offers `remove(word, kind="familiar")` (or `"spelling"`), the call the docstring names as reaching pairs. Each offered call is run by a test and checked to take what the inert one missed. One warning per inert word, the held words of the same call unnamed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, docs/customize.rst giving the recipe. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, which is the intended signal. MEASURED: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move, `remove` not being on the parse path; no shipped pack, plain or strict, warns; in the repository's own tests three removes named readings nothing held, each a test exercising an inert remove on purpose, and none in docs/, README.rst or tools/. OPEN: whether an `add` of a reading the word already holds, with the same properties, deserves the same treatment; it is inert too, but the natural result of copying a recipe. diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 00f190f6c..e9081cfc1 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2583,10 +2583,15 @@ def remove(self, *words: str, kind: str | None = None, edit can never take effect, and the call warns with a ``UserWarning`` naming the kinds the word does hold (#1535); a remove of every word's readings and a ``familiar`` or - ``spelling`` pair remove are not judged. A fragment removing a - reading another lexicon adds when the two are joined warns too, - since this call cannot see that lexicon; filter the warning - around that call. + ``spelling`` pair remove are not judged. The message says which + case it is: a word in the vocabulary without that kind (its + kinds and the call that takes one), a word in no file and no + earlier add, or, with no kind, a word held only as the other + name of another word's ``familiar`` or ``spelling`` pair (the + pair remove that reaches it). A fragment meant to remove a word + another lexicon adds warns, since ``remove`` cannot see the + lexicon it will be joined with: filter that warning by its + message, or do the remove on the joined lexicon. A ``familiar`` or ``spelling`` reading is a pair of given names, stored on one of the two and read by name matching both ways, so @@ -2665,7 +2670,21 @@ def _inert_removes(self, edit: _Edit) -> list[str]: for w in edit.words: held = {r.kind for r in ri.readings_of(w)} | added.get(w, set()) if kind is None: - if not held: + if held: + continue + pair_kind = ("familiar" if self._familiar_forms(w) + else "spelling" if self._alternate_spellings(w) + else None) + if pair_kind is not None: + # held only as the other name of another word's pair, + # which a remove with no kind leaves to that word + messages.append( + f"remove({w!r}) changes nothing: {w!r} holds no " + f"reading of its own, only the other name of " + f"{pair_kind} pairs other words hold; " + f"remove({w!r}, kind={pair_kind!r}) takes those " + f"pairs") + else: messages.append( f"remove({w!r}) changes nothing: {w!r} is in no " f"vocabulary file and no earlier add() of this " diff --git a/tests/v2/test_match.py b/tests/v2/test_match.py index 35c550feb..7503f9b3b 100644 --- a/tests/v2/test_match.py +++ b/tests/v2/test_match.py @@ -2805,12 +2805,32 @@ def test_a_remove_of_every_reading_of_a_word_keeps_the_pairs_other_words_hold() lexicon = _pairs("familiar", "short_for").add("zzbo", kind="title") # zzrobert holds no reading of its own, so the remove takes nothing # and warns (#1535) - with pytest.warns(UserWarning, match="'zzrobert' is in no vocabulary"): + with pytest.warns(UserWarning, + match="'zzrobert' holds no reading of its own"): after = lexicon.remove("zzbo").remove("zzrobert") assert after.readings_of("zzbo") == () assert after._familiar_forms("zzrobert") == {"zzrob"} +@_pair_kinds +def test_a_no_kind_remove_of_a_name_held_only_in_pairs_offers_the_pair_remove( + kind: str, prop: str, outcome: Outcome, + paired: Callable[..., frozenset[str]]) -> None: + # zzsho is the other name of a pair zzlong holds: a remove with no + # kind takes nothing, and the warning offers the remove that takes + # the pair, which this runs (#1535) + lexicon = _pairs(kind, prop) + with pytest.warns(UserWarning) as record: + lexicon.remove("zzsho") + message = str(record[0].message) + assert "'zzsho' holds no reading of its own" in message + offered = re.search(r"remove\('zzsho', kind='[a-z]+'\)", message) + assert offered is not None + taken = eval("lexicon." + offered.group(0)) # noqa: S307 + assert paired(lexicon, "zzsho") == {"zzlong"} + assert paired(taken, "zzsho") == frozenset() + + @_pair_kinds @pytest.mark.parametrize("call, error, match", [ # a bare string is not a list of names, as on add From b76658c25965f5480bedc6d232aa0b55894ffad3 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:46:40 -0800 Subject: [PATCH 4/7] Address the first review round of the remove warning (#1535) The messages: - open with the call and "changes nothing" in every case, so the by-message filter covers them all; - offer a call only where one kind is plainly meant, the single held kind of the asked category or else the single held kind, and never a familiar or spelling kind (dean/particle offered the family reading, don/title a pair remove); - say "in any vocabulary file or earlier add()", the add counting; - find a pair's other name through the reading index as well as the compiled pairs, so robert with a kind and abigail on Lexicon.empty() read as pair names, not as words to check the spelling of; - tell a word held only in the surnames or given_names list how to drop it, with code a test runs; - tell Ph.D., which remove stores as ph.d and the vocabulary as phd, to remove phd: a real no-op the cased and dotted rows turned up; - name the joined-lexicon remedy beside the spelling one; - warn once for a word named twice. Docs: remove's docstring states the cases and that a joined lexicon's adds count; customize.rst's lead names the two common cases, its quoted message updated; the release-log bullet says 3.0.0 through 3.1.0 and keeps one limit sentence; the decisions entry states the five cases and the offer rule, declines an add-repeat warning, which leaves the reading the caller wanted, replaces the Open line, and gains its Standing line; the recipe-doctest lesson moves from root AGENTS.md's validation bullet into docs/AGENTS.md's non-vacuous paragraph, where a docs writer meets it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/AGENTS.md | 2 +- docs/customize.rst | 10 +- docs/design/decisions/vocabulary-model.md | 3 +- docs/release_log.rst | 2 +- nameparser/_lexicon.py | 152 ++++++++++++++-------- tests/v2/test_lexicon.py | 87 ++++++++++++- tests/v2/test_parser.py | 3 +- 8 files changed, 198 insertions(+), 63 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ecab44042..daf642672 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -296,7 +296,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 - **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; every locale pack module (`locales/*.py`) imports `_locale`/`_lexicon`/`_policy`/`_types` and its own private data modules, or its language pack's, in `locales/` only (`es.py` imports `_es_given_names.py`, `es_ar.py` `_es_ar_given_names.py`, and `pt_br.py` and `pt_pt.py` share `_pt_given_names.py`, #1453; `_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), a data module (a leading underscore) imports nothing internal, and the `locales/__init__` additionally lazy-imports its packs (PEP 562). No pack is keyed by hand: the test's `_locale_rules()` holds every file in `locales/` to that rule, a relative import read by the absolute name it resolves to, so a new pack is checked from its first commit. Extend the test's `ALLOWED` table when adding any other module; its completeness checks fail on a `_pipeline/` module it does not key and on a `locales/` module no rule reaches. - **Canonical field order** — the seven roles in `Role` enum declaration order, defined once and derived everywhere (properties, `as_dict`, reprs, `comparison_key`). Never restate the order literally. `Role` is a `StrEnum`: members compare as their field-name strings, and `tokens_for()` coerces strings via `_coerce_enum`. - **Method organization**, fixed section order in every class: fields + `__post_init__` validation → alternative constructors → dunders (construction/equality → protocol → operators) → properties → public methods by concern (access → editing → comparison → rendering delegates) → private helpers last, except a helper serving exactly one section may sit at that section's head. -- **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A recipe's doctest can pass with its edit doing nothing**: an example that removes a reading and then shows a reading true with or without the removal proves nothing, and #1534's review found docs/migrate.rst removing `alhaj` as a religious title (it is a style), the doctest green throughout. Run each recipe's example without its edit too and check that the output moves; `Lexicon.remove` now warns where no file holds the reading named (#1535), which catches that shape, but not an edit that holds a reading the example never reaches. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). +- **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). - **Guard, hint, and emit for the WHOLE family, and parametrize the test over it**: a check added to one member of a set belongs on all of it, and the test must sweep the family, not one example. This session shipped `_reject_str_and_mapping` on `Policy` but not `PolicyPatch`, the bytes decode hint on three of five config entry points, and a regex-sync roster missing four of its copies — each a separate follow-up bug that a `{class} × {field} × {bad-value}` parametrization would have caught and a per-example test hid. When you find you're guarding member N, grep for the other members first. - **Ambiguities are emitted at the DECISION site**: an `Ambiguity` records a fork the parse had to call, not a token that sits in an ambiguous vocabulary, so emit where the branch is taken, in every stage that takes one, and name the reading not taken. The reading TAKEN (`Token.reading`, 3.0) is the one read later, at assemble, where roles are final, from the role and the tags the deciding stages left, its suffix and name sources by the predicates that name the reading not taken. The contract is mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE; the working rules (branches that change nothing, the field a report names, the stages that decide `PARTICLE_OR_GIVEN`, `alternative`, the reading taken, and how to test an emitter) are in `nameparser/_pipeline/AGENTS.md`, which loads when a session reads a pipeline stage. - **A kind is worth adding only if a reader would hesitate too**: the test is not "does the code take a branch" but whether a person reading that input would genuinely be unsure. "Smith, John V." reads as a middle initial to anyone -- the period settles it -- so reporting it would be noise that teaches callers to ignore the field, which costs more than the missing report. Reachability of the second branch is necessary, not sufficient. The example was "Smith, John V" until #877 measured FEC writing that bare letter as a middle initial about as often as letter frequency predicts, where the parser reads the generation: a fork that feels settled is a claim to measure against the data before it decides a report. Prefer leaving a fork silent and documenting the omission over emitting on input nobody finds ambiguous. diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 485064dd0..48c95c570 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -22,7 +22,7 @@ The rules below were distilled from PR #588, which restructured `customize.rst` **A recipe is a doctest; an edge case is a unit test.** A *recipe* — how to do the thing the reader came to do — belongs in the docs as a `.. doctest::` block, which teaches and is CI-checked at once. The line between the two is whether the prose states the behavior: a claim the section makes to the reader (`edd` repairs to `EDD`, not a mask) earns a doctest beside it, which is what keeps the claim true; an edge case the prose has no reason to mention earns one sentence at most and a unit test, never a doctest (PR #216). An example sitting as prose inside a table cell is the worst of both: it teaches from the wrong place and nothing checks it. -**An example must be non-vacuous.** Show the baseline before the customization, and check that they differ: an `add(titles={"chancellor"})` example (2.x's spelling) once shipped (fixed in 0ab19fdb) where `chancellor` was already a default title, so the add was a no-op and the doctest passed demonstrating nothing. Prefer a word absent from the defaults for a teachable reason (`dean`, which is also a given name). +**An example must be non-vacuous.** Show the baseline before the customization, and check that they differ: an `add(titles={"chancellor"})` example (2.x's spelling) once shipped (fixed in 0ab19fdb) where `chancellor` was already a default title, so the add was a no-op and the doctest passed demonstrating nothing. Prefer a word absent from the defaults for a teachable reason (`dean`, which is also a given name). Run each recipe's example without its edit too and check that the output moves: #1534's review found docs/migrate.rst removing `alhaj` as a religious title (it is a style), the doctest green throughout because the output shown held with or without the call. `Lexicon.remove` warns where no file and no earlier add holds the reading named (#1535), which catches that shape, but not an edit that takes a reading the example never reaches. **An example must run warning-free.** Readers paste examples, so a warning the doctest build prints is one every reader gets. Fix the example, not the build: a `Lexicon.empty()` used only to drop titles also dropped the Korean surnames and drew the segmenterless warning, and the fix was an example that empties only the field it is about. Run the doctest build under Verifying below and expect no output at all. diff --git a/docs/customize.rst b/docs/customize.rst index cbd970257..7e8063917 100644 --- a/docs/customize.rst +++ b/docs/customize.rst @@ -169,9 +169,11 @@ its category: >>> Parser(lexicon=lean).parse("Professor Robert Johns").title '' -A remove that can take nothing, a kind the word does not hold or a word -no vocabulary file lists, warns, naming the kinds the word does hold. -``alhaj`` is a style, not a religious title: +A remove that can take nothing warns. One naming a kind the word does +not hold lists the kinds it does, one naming a word no vocabulary file +and no earlier ``add`` lists asks you to check its spelling, and each +opens with the call and "changes nothing". ``alhaj`` is a style, not a +religious title: .. doctest:: @@ -180,7 +182,7 @@ no vocabulary file lists, warns, naming the kinds the word does hold. ... warnings.simplefilter("always") ... inert = Lexicon.default().remove("alhaj", kind="religious") >>> print(caught[0].message) - 'alhaj' has no 'religious' reading in any vocabulary file; its readings are: style. Did you mean remove('alhaj', kind='style')? + remove('alhaj', kind='religious') changes nothing: 'alhaj' has no 'religious' reading in any vocabulary file or earlier add(); it holds: style. Did you mean remove('alhaj', kind='style')? >>> Parser(lexicon=inert).parse("Alhaj Ahmed Khan").title 'Alhaj' diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 4861680dc..8e50cfbdb 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -25,6 +25,7 @@ The vocabulary was a set of base sets plus marker subsets (`particles` and `part - The configure-by-reading API: `add(*words, kind, **properties)` and `remove(*words, kind=None)` (a `familiar` or `spelling` remove also taking the pairs to drop, `short_for=[...]` or `spelling_of=[...]`, 2026-11-15 #1404), the views reading a word's kind from the lexicon, `readings_of` returning a public `LexiconReading` and a repr counting readings by kind, a five-part state (base, ordered edit log, choice, lists, masks) compared structurally, a clash a later choice exposes raised at `parser_for` naming the choice, the choice recorded on the `Lexicon` with chained choices unioning, the default's base lazy, built in 4i-a to 4i-d with no default parse moving; since 3.1 a 2.x pickle is refused, naming the re-pickle under 3.0, and an old spelling refused naming docs/migrate.rst's table of kinds — 2026-11-02 #754, the `Lexicon` surface (Derek); 2026-11-02 #754, sub-phase 4i-a; 2026-11-02 #754, sub-phase 4i-b; 2026-11-02 #754, sub-phase 4i-c; 2026-11-02 #754, sub-phase 4i-d; 2026-11-08 #1003. - A whole kind is taken out with `remove(kind=..., every=True)`, every word's readings of it going, those a later choice turns on included, and `words(kind=..., **properties)` lists the words holding a reading of a kind or category — 2026-11-02 #1007, a kind as a whole (Derek). - Configured by reading, an `add` of a title reading that a `given` reading keeps a title only inside a phrase warns, naming `remove(w, kind="given")`, save one that only updates a held title reading's properties — 2026-11-01 #754, the title warning (Derek). +- A `remove` of a reading no vocabulary file holds, on by default or not, and no earlier `add` of the lexicon gave, warns, its message naming which of five cases it is; a remove of every word's readings and a `familiar` or `spelling` remove are not judged, a fragment removing a word another lexicon adds warns too, and an `add` repeating a held reading does not — 2026-11-22 #1535. - A `Locale` may carry CLDR-shaped render patterns, display and sorting, a later addition whose shape is agreed; how a call reaches one is open — 2026-10-28 #754, render patterns. - 3.0's output model keeps the seven roles and adds every new field as a view, read from `Token.reading`, the reading each token took, or for `surname2` from rules/O6's tag: `generation`, `credentials` and, since 2026-11-03, `honorifics` partitioning `suffix` (decisions/R8), `patronymic`, and `surname2` where rules/O6 read two family names; `middle` and `surnames` keep their meaning, a compound given name being a rule a caller or pack turns on; the default `str()` renders a name in the order it was read in with its written separators in a normalized form, through `render(spec: str | None = None)`, `None` being that default; a language file's `[rules]` compile into its `Locale`'s policy patch — 2026-10-28 #754 (Derek). - `surname2` is read from O6's mark as `Token.reading` publishes it, `Reading.second_surname`, a field not compared, and not from a published tag, which would make an O6 parse unequal to its 2.x pickle (decisions/R10) — 2026-10-29 #754, sub-phase 4d. @@ -654,4 +655,4 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). -- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an earlier `add` in the same lexicon's log gave it; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. The message says which of three cases it is: (i) the word is in the vocabulary but not in that kind, and the message lists its kinds and offers `remove(word, kind=)`; (ii) the word is in no vocabulary file and no earlier add of the lexicon, with no call to offer; (iii) a remove with no kind of a word holding no reading of its own, only the other name of another word's `familiar` or `spelling` pair, and the message offers `remove(word, kind="familiar")` (or `"spelling"`), the call the docstring names as reaching pairs. Each offered call is run by a test and checked to take what the inert one missed. One warning per inert word, the held words of the same call unnamed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, docs/customize.rst giving the recipe. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, which is the intended signal. MEASURED: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move, `remove` not being on the parse path; no shipped pack, plain or strict, warns; in the repository's own tests three removes named readings nothing held, each a test exercising an inert remove on purpose, and none in docs/, README.rst or tools/. OPEN: whether an `add` of a reading the word already holds, with the same properties, deserves the same treatment; it is inert too, but the natural result of copying a recipe. +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is written with full stops inside it where the vocabulary writes it without (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), with the call on the vocabulary's spelling offered; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. diff --git a/docs/release_log.rst b/docs/release_log.rst index 11e1d88f1..44cbc49eb 100644 --- a/docs/release_log.rst +++ b/docs/release_log.rst @@ -46,7 +46,7 @@ Release Log - **Change locales.HR and locales.SL to read two family names, as locales.CS and locales.SK do.** ``parser_for(locales.HR).parse("Ana Puž Kukuljan")`` gives family ``Puž Kukuljan``, where 3.0.0 through 3.1.0 gave middle ``Puž``, family ``Kukuljan``; with no given-name list, a second given name is read as a family name too (``Janez Jože Novak`` gives family ``Jože Novak`` under ``locales.SL``), and a family comma keeps both as before. :issue:`1190` - **Change locales.PT_BR to read two family names, and add locales.PT_PT, which reads names from Portugal the same way.** ``parser_for(locales.PT_BR).parse("Ana Souza Lima")`` gives family ``Souza Lima``, where 3.0.0 through 3.1.0 gave middle ``Souza``, family ``Lima``; a second given name on the packs' Portuguese given-name list stays where it stands (``Ana Beatriz Costa`` keeps family ``Costa``), and ``locales.PT``, chosen for Portuguese names from any country, is unchanged. ``locales.PT_PT`` also reads four given names Portugal writes behind a particle and Brazil does not (``Maria do Rosário Pinto`` gives middle ``do Rosário``, as ``do Carmo``, ``da Conceição`` and ``da Luz`` do). :issue:`1453`, :issue:`1189` - **Change the Spanish given-name lists, rewritten from their tool.** ``parser_for(locales.ES_AR).parse("Juan Gerhard Lopez")`` gives family ``Gerhard Lopez``, where 3.0.0 through 3.1.0 gave middle ``Gerhard``; nine words leave locales.ES_AR's list (``Gerhard``, ``Zuleyma`` among them) and nine join it (``Azhar``, ``Houari``, ``Grace``), each joining reading as a middle name where it read as the first family name, and locales.ES's gains ``Lahcen`` and drops ``Rim``. :issue:`1471`, :issue:`1476` - - **Add a warning when Lexicon.remove names a reading no vocabulary file holds, which took nothing and said nothing.** ``Lexicon.default().remove("alhaj", kind="religious")`` now warns ``'alhaj' has no 'religious' reading in any vocabulary file; its readings are: style. Did you mean remove('alhaj', kind='style')?``, where 3.1.0 returned the lexicon unchanged in silence; a word in no file warns too, while a reading a choice of languages would turn on, or one the same lexicon added earlier, stays silent. A fragment that removes a reading another lexicon adds when the two are joined warns as well, since the call cannot see that lexicon. :issue:`1535` + - **Add a warning when Lexicon.remove names a reading no vocabulary file holds, which took nothing and said nothing.** ``Lexicon.default().remove("alhaj", kind="religious")`` now warns ``remove('alhaj', kind='religious') changes nothing: 'alhaj' has no 'religious' reading in any vocabulary file or earlier add(); it holds: style. Did you mean remove('alhaj', kind='style')?``, where 3.0.0 through 3.1.0 returned the lexicon unchanged in silence. A fragment that removes a word another lexicon adds, when the two are joined, warns too, since the call cannot see that lexicon. :issue:`1535` * 3.1.0 - November 16, 2026 diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 5b64a61cc..a0c10ea6d 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -286,6 +286,19 @@ def _reject_buffer(value: object, label: str, plural: str) -> None: ) +@functools.cache +def _pair_names(category: str) -> frozenset[str]: + """Every name a shipped `category` reading (familiar or spelling) + lists as its pair's other name, `short_for` or `spelling_of`, read + from the reading index once: the names #1535's warning tells apart + from a word in no file, whatever pairs a lexicon has compiled.""" + ri = _index_module() + prop = ri.MATCHING_LISTS[category] + return frozenset( + _normalize(name) for r in ri.index() if r.kind == category + for name in r.props.get(prop) or ()) + + def _warn_at_caller(message: str) -> None: # A fixed stacklevel always lands on library internals: the call # depth differs per entry point (Lexicon(), add(), unpickle, @@ -2589,16 +2602,19 @@ def remove(self, *words: str, kind: str | None = None, Removing a reading the word does not hold changes nothing now, and is kept: a later choice of languages may turn that reading on. Where no vocabulary file holds the reading, on by default or - not, and no earlier :meth:`add` of this lexicon gave it, the - edit can never take effect, and the call warns with a - ``UserWarning`` naming the kinds the word does hold (#1535); a - remove of every word's readings and a ``familiar`` or - ``spelling`` pair remove are not judged. The message says which - case it is: a word in the vocabulary without that kind (its - kinds and the call that takes one), a word in no file and no - earlier add, or, with no kind, a word held only as the other - name of another word's ``familiar`` or ``spelling`` pair (the - pair remove that reaches it). A fragment meant to remove a word + not, and no :meth:`add` earlier in this lexicon's log (a joined + lexicon's included) gave it, the edit can never take effect, and + the call warns with a ``UserWarning`` (#1535); a remove of every + word's readings and a ``familiar`` or ``spelling`` pair remove + are not judged. The message opens with the call and "changes + nothing", and says which case it is: a word holding other kinds + (they are listed, and the call to paste offered where one is + plainly meant, never a pair kind); a word held only in the + ``surnames`` or ``given_names`` list, which ``remove`` does not + edit (the ``dataclasses.replace`` that drops it); a word held + only as the other name of other words' ``familiar`` or + ``spelling`` pairs (the pair remove that reaches them); or a + word in no file and no earlier add. A fragment meant to remove a word another lexicon adds warns, since ``remove`` cannot see the lexicon it will be joined with: filter that warning by its message, or do the remove on the joined lexicon. @@ -2658,14 +2674,16 @@ def remove(self, *words: str, kind: str | None = None, def _inert_removes(self, edit: _Edit) -> list[str]: """A warning for each word of a `remove` that no vocabulary file - and no earlier `add` of this lexicon gives a reading of the kind - asked (any reading, with no kind), so that the edit can take - effect under no choice of languages (#1535). A file's reading - counts whether it is on by default or not, since a choice may - turn it on. Read at `remove` alone, never when a constructor - replays the log or a pickle loads. A remove of every word's - readings (no words) and the familiar and spelling pair removes, - which match names by their folded forms, are not judged.""" + and no `add` earlier in this lexicon's log (a joined lexicon's + included) gives a reading of the kind asked (any reading, with + no kind), so that the edit can take effect under no choice of + languages (#1535). A file's reading counts whether it is on by + default or not, since a choice may turn it on. Read at `remove` + alone, never when a constructor replays the log or a pickle + loads. A remove of every word's readings (no words) and the + familiar and spelling pair removes, which match names by their + folded forms, are not judged. Each message opens with the call + and "changes nothing", so a caller filters one by it.""" ri = _index_module() kind = edit.kind if not edit.words or (kind is not None and ri.CATEGORY.get( @@ -2677,44 +2695,76 @@ def _inert_removes(self, edit: _Edit) -> list[str]: for w in earlier.words: added.setdefault(w, set()).add(earlier.kind) messages = [] - for w in edit.words: + for w in dict.fromkeys(edit.words): held = {r.kind for r in ri.readings_of(w)} | added.get(w, set()) - if kind is None: - if held: - continue - pair_kind = ("familiar" if self._familiar_forms(w) - else "spelling" if self._alternate_spellings(w) - else None) - if pair_kind is not None: - # held only as the other name of another word's pair, - # which a remove with no kind leaves to that word - messages.append( - f"remove({w!r}) changes nothing: {w!r} holds no " - f"reading of its own, only the other name of " - f"{pair_kind} pairs other words hold; " - f"remove({w!r}, kind={pair_kind!r}) takes those " - f"pairs") - else: - messages.append( - f"remove({w!r}) changes nothing: {w!r} is in no " - f"vocabulary file and no earlier add() of this " - f"lexicon; check its spelling") - continue - if any(k == kind or ri.CATEGORY[k] == kind for k in held): + if kind is None and held: continue - if not held: - messages.append( - f"remove({w!r}, kind={kind!r}) changes nothing: {w!r} " - f"is in no vocabulary file and no earlier add() of " - f"this lexicon; check its spelling") + if kind is not None and any( + k == kind or ri.CATEGORY[k] == kind for k in held): continue - kinds = sorted(held) - messages.append( - f"{w!r} has no {kind!r} reading in any vocabulary file; " - f"its readings are: {', '.join(kinds)}. Did you mean " - f"remove({w!r}, kind={kinds[0]!r})?") + call = (f"remove({w!r})" if kind is None + else f"remove({w!r}, kind={kind!r})") + head = f"{call} changes nothing: " + if held: + messages.append(head + self._other_kinds(w, kind, held)) + else: + messages.append(head + self._no_reading(w, kind)) return messages + def _other_kinds(self, w: str, kind: str | None, + held: set[str]) -> str: + """Case (i) of #1535: the word holds readings, none of `kind`. + The call to paste is offered only where one kind is plainly the + one meant: the single held kind of the asked kind's category, + else the single held kind of all; a familiar or spelling kind is + never offered, its remove reaching name matching's pairs.""" + ri = _index_module() + kinds = sorted(held) + candidates = [k for k in kinds if ri.CATEGORY[k] not in + ri.MATCHING_ONLY] + same = [k for k in candidates + if ri.CATEGORY[k] == ri.CATEGORY.get(kind or "", kind)] + offer = (same[0] if len(same) == 1 else + candidates[0] if not same and len(candidates) == 1 else None) + text = (f"{w!r} has no {kind!r} reading in any vocabulary file or " + f"earlier add(); it holds: {', '.join(kinds)}") + if offer is not None: + text += f". Did you mean remove({w!r}, kind={offer!r})?" + return text + + def _no_reading(self, w: str, kind: str | None) -> str: + """Cases (ii) and (iii) of #1535: the word holds no reading. It + may stand in the two lists, which remove() does not edit, be + only the other name of other words' familiar or spelling pairs, + which a remove of the pair kind takes, or be written with full + stops inside it where the vocabulary writes the word without + (``ph.d``, held as ``phd``); else it is in no file.""" + for list_field in ("surnames", "given_names"): + if w in getattr(self, list_field): + return (f"{w!r} holds no reading, only an entry in this " + f"lexicon's {list_field} list, which remove() does " + f"not edit; drop it with dataclasses.replace(" + f"lexicon, {list_field}=lexicon.{list_field} - " + f"{{{w!r}}})") + pair_kind = ("familiar" if self._familiar_forms(w) + or w in _pair_names("familiar") else + "spelling" if self._alternate_spellings(w) + or w in _pair_names("spelling") else None) + if pair_kind is not None: + return (f"{w!r} holds no reading of its own, only the other " + f"name of {pair_kind} pairs other words hold; " + f"remove({w!r}, kind={pair_kind!r}) takes those pairs") + bare = w.replace(".", "") + if bare != w and _index_module().readings_of(bare): + call = (f"remove({bare!r})" if kind is None + else f"remove({bare!r}, kind={kind!r})") + return (f"the vocabulary writes {w!r} without its full stops, " + f"as {bare!r}: did you mean {call}?") + return (f"{w!r} is in no vocabulary file and no earlier add() of " + f"this lexicon; check its spelling, or, where a lexicon " + f"this one is joined with adds it, remove it from the " + f"joined lexicon") + def _pool(self) -> Pool: return self._files.pool() diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 62f2c0132..f48514832 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -2260,12 +2260,85 @@ def test_a_remove_that_takes_nothing_warns( assert len(removed._edits) == 1 +_MESSAGE_CASES = [ + # several kinds held, none in the asked category: no call offered + pytest.param(lambda L: L.remove("dean", kind="particle"), + "it holds: family, given, office", None, id="several-kinds"), + # the asked category's one held kind is offered + pytest.param(lambda L: L.remove("dean", kind="religious"), + "it holds: family, given, office", "remove('dean', kind='office')", + id="same-category"), + # a pair kind is never offered: its remove reaches name matching + pytest.param(lambda L: L.remove("don", kind="title"), + "it holds: familiar", None, id="pair-kind-only"), + pytest.param(lambda L: L.remove("olha", kind="given"), + "it holds: spelling", None, id="spelling-only"), + # a kind held through the lexicon's own earlier add + pytest.param(lambda L: L.add("zzq", kind="office").remove("zzq", kind="family"), + "in any vocabulary file or earlier add(); it holds: office", + "remove('zzq', kind='office')", id="own-add-other-kind"), + # a name held only as other words' pairs, with a kind and on an empty + # lexicon, which has compiled no pairs + pytest.param(lambda L: L.remove("robert", kind="given"), + "'robert' holds no reading of its own", + "remove('robert', kind='familiar')", id="pair-name-kind"), + pytest.param(lambda L: Lexicon.empty().remove("abigail"), + "'abigail' holds no reading of its own", + "remove('abigail', kind='familiar')", id="pair-name-empty"), + # full stops inside a word the vocabulary writes without them + pytest.param(lambda L: L.remove("Ph.D.", kind="credential"), + "the vocabulary writes 'ph.d' without its full stops", + "remove('phd', kind='credential')", id="interior-stops"), + # a word in no file: the join remedy named beside the spelling one + pytest.param(lambda L: L.remove("zzyzx", kind="title"), + "remove it from the joined lexicon", None, id="no-file"), +] + + +@pytest.mark.parametrize("call, part, offered", _MESSAGE_CASES) +def test_a_remove_warning_names_its_case( + call: Callable[[Lexicon], Lexicon], part: str, + offered: str | None) -> None: + with pytest.warns(UserWarning) as record: + call(Lexicon.default()) + message = str(record[0].message) + # every case opens with the call and "changes nothing", the text a + # caller filters one by + assert re.match(r"remove\('[^']+'(, kind='[a-z_]+')?\) changes nothing: ", + message), message + assert part in message, message + found = re.findall(r"remove\('[^']+', kind='[a-z_]+'\)", message.split( + "changes nothing: ", 1)[1]) + assert found == ([offered] if offered else []), message + + +@pytest.mark.parametrize("field", ["surnames", "given_names"]) +def test_a_word_held_only_in_a_list_is_told_how_to_drop_it(field: str) -> None: + listed = frozenset({"zzluis"}) + lexicon = (dataclasses.replace(Lexicon.default(), surnames=listed) + if field == "surnames" else + dataclasses.replace(Lexicon.default(), given_names=listed)) + with pytest.warns(UserWarning) as record: + lexicon.remove("zzluis") + message = str(record[0].message) + assert f"this lexicon's {field} list" in message + offered = re.search(r"dataclasses\.replace\(.*\}\)", message) + assert offered is not None + dropped = eval(offered.group(0)) # noqa: S307 + assert "zzluis" in getattr(lexicon, field) + assert "zzluis" not in getattr(dropped, field) + + def test_a_remove_of_several_words_names_only_those_it_takes_nothing_from() -> None: with pytest.warns(UserWarning) as record: Lexicon.default().remove("alhaj", "qari", "zzyzx", kind="religious") messages = [str(w.message) for w in record] assert len(messages) == 2 assert any("'alhaj'" in m for m in messages) + # a word named twice in one call warns once + with pytest.warns(UserWarning) as twice: + Lexicon.default().remove("alhaj", "alhaj", kind="religious") + assert len(twice) == 1 assert any("'zzyzx'" in m for m in messages) assert not any("'qari'" in m for m in messages) @@ -2275,9 +2348,10 @@ def test_the_remove_a_warning_offers_takes_the_reading() -> None: # check that it takes the reading the inert one missed with pytest.warns(UserWarning) as record: Lexicon.default().remove("alhaj", kind="religious") - offered = re.search(r"remove\([^)]*\)", str(record[0].message)) + offered = re.search(r"Did you mean (remove\([^)]*\))", + str(record[0].message)) assert offered is not None - fixed = eval("Lexicon.default()." + offered.group(0)) # noqa: S307 + fixed = eval("Lexicon.default()." + offered.group(1)) # noqa: S307 assert "style" in {r.kind for r in Lexicon.default().readings_of("alhaj")} assert "style" not in {r.kind for r in fixed.readings_of("alhaj")} assert Parser(lexicon=fixed).parse("Alhaj Ahmed Khan").title == "" @@ -2297,9 +2371,16 @@ def test_the_remove_a_warning_offers_takes_the_reading() -> None: .remove("zzorvan", kind="family"), id="own-add-twice"), pytest.param(lambda L: L.remove("phd", kind="credential") .remove("phd", kind="credential"), id="file-twice"), + # the word as the lexicon stores it: case and full stops folded, as + # for an earlier add of the caller's own + pytest.param(lambda L: L.remove("Dean", kind="title"), id="cased"), + pytest.param(lambda L: L.remove("Dean.", kind="title"), id="dotted"), + pytest.param(lambda L: L.add("zzk", kind="family") + .remove("ZZK", kind="family"), id="own-add-cased"), # a remove of every word's readings of a kind names no word pytest.param(lambda L: L.remove(kind="title", every=True), id="every"), - # the pair removes are judged by name matching's folded forms + # the pair removes are not judged: they match by name matching's + # folded forms, which this check does not read pytest.param(lambda L: L.remove("zzbob", kind="familiar"), id="familiar"), pytest.param(lambda L: L.remove("zzsara", kind="spelling", diff --git a/tests/v2/test_parser.py b/tests/v2/test_parser.py index 18dfec736..38039119e 100644 --- a/tests/v2/test_parser.py +++ b/tests/v2/test_parser.py @@ -3264,7 +3264,8 @@ def test_a_packs_fragment_joins_under_the_callers_lexicon() -> None: first = _choosing("en", code="aa", lexicon=Lexicon.empty().add("zzq", kind="title")) # the fragment's remove takes out a reading another lexicon adds, which - # remove() cannot see, so it warns that no file holds it (#1535) + # remove() cannot see, so it warns that no file and no earlier add + # of its own lexicon holds it (#1535) with pytest.warns(UserWarning, match="'zzq' is in no vocabulary file"): second = _choosing("en", code="bb", lexicon=Lexicon.empty().remove("zzq", kind="title")) From 1836fb0953b8aece6027ab5161d8d30d412abfe4 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:54:33 -0800 Subject: [PATCH 5/7] Narrow the remove warning's full-stop and list cases (#1535) Review of the fix commit found the full-stop case offering another word: remove("j.r.") was offered remove("jr"), though the parse never reads J.R. as jr, and that remove changes how Jr. reads; and it ignored the kind asked, so remove("m.d.", kind="title") offered a remove that takes nothing either. It now fires only where the bare word is a suffix acronym or a dotted title, the spellings the parse reads with their stops dropped, and holds the kind asked; else the word is reported as in no file. The list case offers dropping the entry only where the kind asked is the list's (family or name for the surnames, given or name for the given names). Test rows hold j.r. and m.d. as a title in case (v). Co-Authored-By: Claude Opus 5.5 --- docs/design/decisions/vocabulary-model.md | 2 +- nameparser/_lexicon.py | 25 +++++++++++++++++------ tests/v2/test_lexicon.py | 7 +++++++ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 8e50cfbdb..7c5fbbae7 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -655,4 +655,4 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). -- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is written with full stops inside it where the vocabulary writes it without (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), with the call on the vocabulary's spelling offered; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the bare word holds the kind asked, with the call on the vocabulary's spelling offered; a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`), and offers nothing; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index a0c10ea6d..23578bd78 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2736,11 +2736,16 @@ def _no_reading(self, w: str, kind: str | None) -> str: """Cases (ii) and (iii) of #1535: the word holds no reading. It may stand in the two lists, which remove() does not edit, be only the other name of other words' familiar or spelling pairs, - which a remove of the pair kind takes, or be written with full - stops inside it where the vocabulary writes the word without - (``ph.d``, held as ``phd``); else it is in no file.""" - for list_field in ("surnames", "given_names"): - if w in getattr(self, list_field): + which a remove of the pair kind takes, or be a suffix acronym or + a dotted title written with its full stops (``ph.d``, held as + ``phd``), where the bare word holds the kind asked; else it is + in no file.""" + ri = _index_module() + lists = {"surnames": ("family", "name"), "given_names": ("given", "name")} + for list_field, kinds in lists.items(): + if w in getattr(self, list_field) and ( + kind is None or kind in kinds + or ri.CATEGORY.get(kind) == kinds[0]): return (f"{w!r} holds no reading, only an entry in this " f"lexicon's {list_field} list, which remove() does " f"not edit; drop it with dataclasses.replace(" @@ -2754,8 +2759,16 @@ def _no_reading(self, w: str, kind: str | None) -> str: return (f"{w!r} holds no reading of its own, only the other " f"name of {pair_kind} pairs other words hold; " f"remove({w!r}, kind={pair_kind!r}) takes those pairs") + # only where the parse reads the dotted spelling as the bare word: + # a suffix acronym (M.D. as md) or a dotted title (U.S. as us), + # and the bare word holds the kind asked bare = w.replace(".", "") - if bare != w and _index_module().readings_of(bare): + bare_kinds = {r.kind for r in ri.readings_of(bare)} + if (bare != w and bare in (self._sets.suffix_acronyms + | self._sets.dotted_titles) + and (kind is None or any( + k == kind or ri.CATEGORY[k] == kind + for k in bare_kinds))): call = (f"remove({bare!r})" if kind is None else f"remove({bare!r}, kind={kind!r})") return (f"the vocabulary writes {w!r} without its full stops, " diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index f48514832..052e70195 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -2289,6 +2289,13 @@ def test_a_remove_that_takes_nothing_warns( pytest.param(lambda L: L.remove("Ph.D.", kind="credential"), "the vocabulary writes 'ph.d' without its full stops", "remove('phd', kind='credential')", id="interior-stops"), + # a suffix word with stops is no acronym (J.R. is not read as jr), and + # a bare word not holding the kind asked offers nothing + pytest.param(lambda L: L.remove("j.r."), "'j.r' is in no vocabulary file", + None, id="stops-not-an-acronym"), + pytest.param(lambda L: L.remove("m.d.", kind="title"), + "'m.d' is in no vocabulary file", None, + id="stops-other-kind"), # a word in no file: the join remedy named beside the spelling one pytest.param(lambda L: L.remove("zzyzx", kind="title"), "remove it from the joined lexicon", None, id="no-file"), From 612d7ecf908684895539e838d96480bfc327654c Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 12:59:09 -0800 Subject: [PATCH 6/7] Offer the reading a dotted spelling is read by, and count the lexicon's adds there (#1535) Review of the narrowing found remove("M.D.") offering remove("md"), which also takes md's given reading (Muhammad written short) and moves "Md. Ali Khan"; with no kind asked the full-stop case now names the kind the dotted spelling is read by, the suffix acronym's suffix reading or the dotted title's title one, offering remove("md", kind="credential"). The bare word's kinds now count the lexicon's own earlier adds, as the word's do, so an acronym a caller added (xq) is offered and not reported as in no file. The list case's third test, which could never hold, is gone. Co-Authored-By: Claude Opus 5.5 --- docs/design/decisions/vocabulary-model.md | 2 +- nameparser/_lexicon.py | 24 ++++++++++++++--------- tests/v2/test_lexicon.py | 10 ++++++++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 7c5fbbae7..320825d2a 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -655,4 +655,4 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). -- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the bare word holds the kind asked, with the call on the vocabulary's spelling offered; a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`), and offers nothing; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the bare word, in the files or an earlier add, holds the kind asked, with the call on the vocabulary's spelling offered, naming with no kind asked the kind the dotted spelling is read by (`remove("M.D.")` offers `remove("md", kind="credential")`, leaving `md`'s given reading, Muhammad written short); a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`), and offers nothing; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 23578bd78..9ba5fa385 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2708,7 +2708,7 @@ def _inert_removes(self, edit: _Edit) -> list[str]: if held: messages.append(head + self._other_kinds(w, kind, held)) else: - messages.append(head + self._no_reading(w, kind)) + messages.append(head + self._no_reading(w, kind, added)) return messages def _other_kinds(self, w: str, kind: str | None, @@ -2732,7 +2732,8 @@ def _other_kinds(self, w: str, kind: str | None, text += f". Did you mean remove({w!r}, kind={offer!r})?" return text - def _no_reading(self, w: str, kind: str | None) -> str: + def _no_reading(self, w: str, kind: str | None, + added: dict[str, set[str]]) -> str: """Cases (ii) and (iii) of #1535: the word holds no reading. It may stand in the two lists, which remove() does not edit, be only the other name of other words' familiar or spelling pairs, @@ -2744,8 +2745,7 @@ def _no_reading(self, w: str, kind: str | None) -> str: lists = {"surnames": ("family", "name"), "given_names": ("given", "name")} for list_field, kinds in lists.items(): if w in getattr(self, list_field) and ( - kind is None or kind in kinds - or ri.CATEGORY.get(kind) == kinds[0]): + kind is None or kind in kinds): return (f"{w!r} holds no reading, only an entry in this " f"lexicon's {list_field} list, which remove() does " f"not edit; drop it with dataclasses.replace(" @@ -2763,14 +2763,20 @@ def _no_reading(self, w: str, kind: str | None) -> str: # a suffix acronym (M.D. as md) or a dotted title (U.S. as us), # and the bare word holds the kind asked bare = w.replace(".", "") - bare_kinds = {r.kind for r in ri.readings_of(bare)} + bare_kinds = ({r.kind for r in ri.readings_of(bare)} + | added.get(bare, set())) + # the kind the dotted spelling is read by: a suffix acronym's + # suffix reading, a dotted title's title one (M.D. is md's + # credential, not its given reading, Muhammad written short) + read_as = {k for k in bare_kinds if ri.CATEGORY[k] == ( + "suffix" if bare in self._sets.suffix_acronyms else "title")} if (bare != w and bare in (self._sets.suffix_acronyms | self._sets.dotted_titles) - and (kind is None or any( + and (kind is None and len(read_as) == 1 or any( k == kind or ri.CATEGORY[k] == kind - for k in bare_kinds))): - call = (f"remove({bare!r})" if kind is None - else f"remove({bare!r}, kind={kind!r})") + for k in read_as))): + offer = kind if kind is not None else next(iter(read_as)) + call = f"remove({bare!r}, kind={offer!r})" return (f"the vocabulary writes {w!r} without its full stops, " f"as {bare!r}: did you mean {call}?") return (f"{w!r} is in no vocabulary file and no earlier add() of " diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 052e70195..83840c397 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -2289,6 +2289,16 @@ def test_a_remove_that_takes_nothing_warns( pytest.param(lambda L: L.remove("Ph.D.", kind="credential"), "the vocabulary writes 'ph.d' without its full stops", "remove('phd', kind='credential')", id="interior-stops"), + # with no kind, the kind the dotted spelling is read by: md's + # credential, not its given reading (Muhammad written short) + pytest.param(lambda L: L.remove("M.D."), + "the vocabulary writes 'm.d' without its full stops", + "remove('md', kind='credential')", id="stops-no-kind"), + # an acronym the lexicon's own earlier add gave + pytest.param(lambda L: L.add("xq", kind="credential", acronym=True) + .remove("x.q.", kind="credential"), + "the vocabulary writes 'x.q' without its full stops", + "remove('xq', kind='credential')", id="stops-own-add"), # a suffix word with stops is no acronym (J.R. is not read as jr), and # a bare word not holding the kind asked offers nothing pytest.param(lambda L: L.remove("j.r."), "'j.r' is in no vocabulary file", From aff3a9292df5b3be27e8901eaaad4e523158e0a2 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Sun, 22 Nov 2026 13:06:34 -0800 Subject: [PATCH 7/7] Name the bare spelling whenever a dotted word is an acronym or dotted title (#1535) Review of 612d7ecf found a dotted acronym or title falling to "in no vocabulary file" where no call was plainly meant (us read by two title kinds after a caller's add; M.D. asked as given, Ph.D. as title); the message now always names the bare word, offers the call where one kind is plainly meant, and otherwise lists the kinds the dotted spelling is read by. Tests now run the full-stop offers: remove('md', kind='credential') takes M.D.'s suffix and leaves "Md. Ali Khan" given, and an added acronym's offer takes it. The decisions entry states case (iv)'s condition as the code reads it, and records as accepted that rules/S3's dotted shape still reads Ph.D. as a suffix after the offered remove takes the vocabulary's reading. Co-Authored-By: Claude Opus 5.5 --- docs/design/decisions/vocabulary-model.md | 2 +- nameparser/_lexicon.py | 26 +++++++++------ tests/v2/test_lexicon.py | 39 +++++++++++++++++++++-- 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 320825d2a..fdbfa70ca 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -655,4 +655,4 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The pairs re-taken here stay ungated, as wanted:** under a strict choice the word is the particle that language writes. Re-taken 2026-11-21 on `81a24221` by the same score with each tag's ungated words given back their `given` reading: `ben` under strict `ar` fixes 62 records (Tunisia 45, Algeria 9, Morocco 8), `bin` under strict `ms` 6 (ORCID 2, PatentsView 4), `del`, `la`, `san` and `santa` under strict `it` 7, `del`, `la` and `san` under strict `fil` 2, `da`, `do` and `santa` under strict `pt-BR` 1, each breaking none. Read record by record, nearly all are a family name written first with the boxes filed that way round (`Ben Amri Salma`, given box `Ben Amri`): strict reads the whole name as the family (rules/P1's fold, `Ben Amri Salma` → family 'Ben Amri Salma'), wrong too, and the gate agrees with the boxes only because it reads the first word as a given name, so neither reading is the name and the gate's is no better. The rest are a given name the particle is spelled like: of another origin (`Bin Qiaoyu`, the Chinese given name, in Malaysia; `La Thuy`), a cost accepted under strict's premise that its data is of one origin (docs/locales.rst, "Reading one language only": strict is "for data you know to be of one origin"), which answers the issue's second question for `Bin`; and one of the language's own (`La Reina Dimaculangan`, a Philippine given name), a cost of reading `la` as the particle that the premise does not answer, left with the pair. - **Not weighed here:** the rest of `STRICT_UNGATED`, which stays as it was: `gd`, `hr`, `sk`, `sl` and `hi`, and `marquis`, `marquise`, `tho`, `st` and `sushri`, which the issue's samples held too rarely to say anything (its first open question); the pairs of `nl`, `fr`, `ca` and `ga`, which moved none of the 822 records the issue's table read for them, so no reading of a record weighs them; `pt` and `pt-PT` (the issue's table read `pt` with `pt-BR` and holds no `pt-PT`; only `pt-BR` is re-taken here); and `my`'s ranks, which joined after the issue (#1483) and are titles, not particles, their given names written only in en.toml. None is decided as wanted by this entry (#1463). -- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the bare word, in the files or an earlier add, holds the kind asked, with the call on the vocabulary's spelling offered, naming with no kind asked the kind the dotted spelling is read by (`remove("M.D.")` offers `remove("md", kind="credential")`, leaving `md`'s given reading, Muhammad written short); a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`), and offers nothing; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. +- 2026-11-22 #1535 — `Lexicon.remove` WARNS WHERE NO VOCABULARY FILE HOLDS THE READING IT NAMES, AND NO EARLIER `add` OF THE LEXICON GAVE IT. Decided 2026-11-22. A remove of a kind the word does not hold, or of a word in no file, took nothing and said nothing, so it could not be told from a working one: docs/migrate.rst's recipe removed `alhaj` as `kind="religious"`, a style, and its doctest passed because the assertion shown held with or without the call (found by #1534's review). THE RULE: for each word of `remove(*words, kind=...)`, the kinds held are every kind the reading index gives the word (`_reading_index.readings_of`, every file's rows whether on by default or not, the word looked up as `remove` stores it) and every kind an `add` earlier in the lexicon's log gave it, a joined lexicon's included; the call warns where no held kind is the one asked or, for a category, of it, and with no kind where the word holds none. A word named twice in one call warns once. THE MESSAGE opens with the call and "changes nothing", so a caller filters one by it, and names its case: (i) the word holds other kinds, listed, with `remove(word, kind=K)` offered only where one kind is plainly meant (the single held kind of the asked kind's category, else the single held kind of all) and never a `familiar` or `spelling` kind, whose remove reaches name matching's pairs; (ii) the word holds no reading but stands in the `surnames` or `given_names` list, which `remove` does not edit, and the kind asked is the list's (none, `family` or `name` for the surnames, none, `given` or `name` for the given names), with the `dataclasses.replace` that drops it offered; (iii) it holds no reading of its own but is the other name of other words' `familiar` or `spelling` pairs, found in the reading index as well as the lexicon's compiled pairs, with the pair remove offered; (iv) it is a suffix acronym or a dotted title written with its full stops, the spellings the parse reads as the bare word (`remove("Ph.D.", kind="credential")`, stored `ph.d`, the vocabulary's `phd`), and the message names the bare word; it offers the call on the bare word where the reading the dotted spelling is read by (the bare word's suffix reading if it is a suffix acronym, else its title reading, in the files or an earlier add) is of the kind asked, or, with no kind asked, is of exactly one kind, which the call names (`remove("M.D.")` offers `remove("md", kind="credential")`, leaving `md`'s given reading, Muhammad written short), and otherwise lists the kinds the dotted spelling is read by and offers nothing; a suffix word written with stops is no such spelling (`J.R.` is not read as `jr`). Accepted: the offered call takes the vocabulary's reading, while rules/S3's dotted shape (`Policy.unlisted_dotted_suffixes`) still reads `Ph.D.` or `D.D.S.` as a suffix by its shape; (v) it is in no file and no earlier add, and the message says to check its spelling or, where a lexicon this one is joined with adds it, to remove it from the joined lexicon. Each offered call is run by a test and checked to take what the inert one missed. Not judged: a remove with no words (`every=True`), and the `familiar` and `spelling` pair removes, which match by folded forms through name matching's index. WHERE: in `Lexicon.remove` alone, through `_warn_at_caller`, so it names the caller's own line through a chained call and inside `Parser(lexicon=...)`; never where a constructor replays the log or a pickle loads. WHY A WARNING: the edit misparses nothing, so a raise is wrong by the invariants rule (AGENTS.md: invariants guard harm, not no-ops), and it is statically decidable and indistinguishable from a working edit, the construction-time warning's case. ACCEPTED, decided 2026-11-22 over staying silent on a fragment built on `Lexicon.empty()`, which would have cost every hand-built fragment its typo check, packs included: a fragment meant to remove a word another lexicon adds warns, since `remove` cannot see the lexicon it will be joined with (tests/v2/test_parser.py's pack-fragment join asserts it); its caller filters that warning by its message, never by category, or does the remove on the joined lexicon, as case (v)'s message and docs/customize.rst say. A fragment removing a file's reading, which is how a pack is written, stays silent. A word spelled in a way the fold does not reach warns as unknown, the intended signal. DECLINED: the same warning on an `add` of a reading the word already holds with the same properties, the issue's open point. An inert remove leaves a reading the caller wanted gone, so the parse is not what they asked for; a redundant add leaves the reading the caller wanted present, so the parse is what they asked for, and its usual cause is a recipe a later release made unnecessary, so the warning would fire on working code after an upgrade each time a release ships a word a caller had added, teaching callers to ignore it. MEASURED on `ffc5d23c` with this change: no parse moves (`tools/differential/snapshot.jsonl` byte-identical), and the reference parse's frames do not move (`tools/perf/call_count.py --against origin/master`: 195.72 on py3.11 both sides), `remove` not being on the parse path; no shipped pack, plain or strict, warns; outside this change's own tests, three removes in the tests named readings nothing held (tests/v2/test_lexicon.py's remove-before-add, test_match.py's `zzrobert`, test_parser.py's pack fragment), each exercising an inert remove on purpose; in docs/, README.rst and tools/, none besides the two examples docs/customize.rst adds to show the warning. diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 9ba5fa385..15d492172 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2770,15 +2770,23 @@ def _no_reading(self, w: str, kind: str | None, # credential, not its given reading, Muhammad written short) read_as = {k for k in bare_kinds if ri.CATEGORY[k] == ( "suffix" if bare in self._sets.suffix_acronyms else "title")} - if (bare != w and bare in (self._sets.suffix_acronyms - | self._sets.dotted_titles) - and (kind is None and len(read_as) == 1 or any( - k == kind or ri.CATEGORY[k] == kind - for k in read_as))): - offer = kind if kind is not None else next(iter(read_as)) - call = f"remove({bare!r}, kind={offer!r})" - return (f"the vocabulary writes {w!r} without its full stops, " - f"as {bare!r}: did you mean {call}?") + if bare != w and bare in (self._sets.suffix_acronyms + | self._sets.dotted_titles): + text = (f"the vocabulary writes {w!r} without its full stops, " + f"as {bare!r}") + asked = [k for k in read_as if kind is not None + and (k == kind or ri.CATEGORY[k] == kind)] + if kind is None and len(read_as) == 1: + offer: str | None = next(iter(read_as)) + elif len(asked) == 1: + offer = kind + else: + offer = None + if offer is not None: + return text + (f": did you mean remove({bare!r}, " + f"kind={offer!r})?") + return text + (", read with its full stops as " + + ", ".join(sorted(read_as))) return (f"{w!r} is in no vocabulary file and no earlier add() of " f"this lexicon; check its spelling, or, where a lexicon " f"this one is joined with adds it, remove it from the " diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 83840c397..11025bff8 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -2300,11 +2300,11 @@ def test_a_remove_that_takes_nothing_warns( "the vocabulary writes 'x.q' without its full stops", "remove('xq', kind='credential')", id="stops-own-add"), # a suffix word with stops is no acronym (J.R. is not read as jr), and - # a bare word not holding the kind asked offers nothing + # a kind the dotted spelling is not read by names the one it is pytest.param(lambda L: L.remove("j.r."), "'j.r' is in no vocabulary file", None, id="stops-not-an-acronym"), pytest.param(lambda L: L.remove("m.d.", kind="title"), - "'m.d' is in no vocabulary file", None, + "as 'md', read with its full stops as credential", None, id="stops-other-kind"), # a word in no file: the join remedy named beside the spelling one pytest.param(lambda L: L.remove("zzyzx", kind="title"), @@ -2329,6 +2329,41 @@ def test_a_remove_warning_names_its_case( assert found == ([offered] if offered else []), message +def test_a_dotted_spellings_offer_takes_only_the_reading_it_is_read_by() -> None: + # M.D. is md's credential, and md is also Muhammad written short: the + # offered call takes the credential and leaves the given name (#1535) + with pytest.warns(UserWarning) as record: + Lexicon.default().remove("M.D.") + offered = re.search(r"did you mean (remove\([^)]*\))", + str(record[0].message)) + assert offered is not None + taken = Parser(lexicon=eval("Lexicon.default()." + offered.group(1))) # noqa: S307 + assert Parser().parse("John Smith M.D.").suffix == "M.D." + assert taken.parse("John Smith M.D.").suffix == "" + assert taken.parse("Md. Ali Khan").given == "Md." + # an acronym the lexicon added itself, offered and taken the same way + added = Lexicon.default().add("xq", kind="credential", acronym=True) + with pytest.warns(UserWarning) as own: + added.remove("x.q.") + offered = re.search(r"did you mean (remove\([^)]*\))", str(own[0].message)) + assert offered is not None + assert Parser(lexicon=added).parse("Jane Doe XQ").suffix == "XQ" + assert Parser(lexicon=eval("added." + offered.group(1))).parse( # noqa: S307 + "Jane Doe XQ").suffix == "" + + +def test_a_dotted_spelling_read_by_two_kinds_lists_them() -> None: + # us is a dotted title read by two title kinds once a caller adds one, + # so no call is plainly meant: the kinds are listed, none offered + lexicon = Lexicon.default().add("us", kind="academic") + with pytest.warns(UserWarning) as record: + lexicon.remove("u.s.") + message = str(record[0].message) + assert "the vocabulary writes 'u.s' without its full stops" in message + assert "read with its full stops as academic, modifier" in message + assert "did you mean" not in message + + @pytest.mark.parametrize("field", ["surnames", "given_names"]) def test_a_word_held_only_in_a_list_is_told_how_to_drop_it(field: str) -> None: listed = frozenset({"zzluis"})