Repository navigation
fix: read non-ASCII digits in NumericComparator - #560
Conversation
|
Before/after for review: the same inputs through
Every all-ASCII row is unchanged, because ASCII input skips the new step. The one result that goes from 1.0 to 0.0 is the false match. One behaviour to be aware of: a string that uses non-ASCII digits as a label, such as Scriptfrom stickler.comparators import NumericComparator
n = NumericComparator()
cases = [("1250", "١٢٥٠"), ("1250", "۱۲۵۰"), ("1250", "१२५०"), ("1250", "১২৫০"),
("1250", "๑๒๕๐"), ("1250", "1250"), ("1,250.00", "١٬٢٥٠٫٠٠"),
("AED 1,250.50", "١٬٢٥٠٫٥٠ درهم"), ("-1250", "(١٢٥٠)"), (1250, "١٢٥٠"),
("0.5", "١٢٥٠.50"), ("1250", "١٢٥١"), ("2", "²"), ("1", "①"),
("123", "123.0"), ("$123", "123"), ("123,456", "123456"), ("123", "456"),
(None, None)]
for a, b in cases:
print(repr(a), repr(b), n.compare(a, b))
t = NumericComparator(relative_tolerance=0.1)
print(t.compare("100", "١٠٩"), t.compare("100", "١١١")) |
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
The fix for #559 works, and every row of the PR body's table reproduces. In three cases, though, values that dev read as no number (score 0.0) are now read as the wrong number and score 1.0. Measured at head 88ea9f9, with NumericComparator().compare:
PR dev
'1250.5' vs '−۱٬۲۵۰٫۵' (ICU fa -1250.5) 1.0 0.0
'1250' vs '−١٢٥٠' 1.0 0.0
'125050' vs '1250.50' 1.0 0.0
'1250' vs '-1250' 1.0 0.0
'1250.00' vs '1,250.00 (١٬٢٥٠٫٠٠)' 0.0 1.0
stickler/src/stickler/comparators/numeric.py
Lines 15 to 32 in 88ea9f9
stickler/src/stickler/comparators/numeric.py
Lines 141 to 148 in 88ea9f9
1. Persian and Arabic negatives read as positive. _to_ascii_digits does not map U+2212 MINUS SIGN. CLDR and ICU put that sign on Persian negatives, and the [^0-9.-] filter then deletes it. The accounting check also runs before the invisible direction mark (U+200E) is removed, so ICU's Persian accounting format ($ ۱٬۲۵۰٫۵۰) reads as +1250.50. Fix: map U+2212 to -, and remove category Cf characters and outer whitespace before the parenthesis check.
2. Fullwidth punctuation is not mapped. The docstring says fullwidth is supported, but only fullwidth digits are rewritten. So 1250.50 reads 125050, and -1250 and (1250) read as +1250. Fix: map U+FF01–U+FF5E to ASCII (code point − 0xFEE0). Do not use NFKC, because it turns ² into 2, which test_non_decimal_digit_characters_are_not_numbers forbids.
3. Bilingual amounts that matched on dev now fail. Non-ASCII digits elsewhere in the string now join the number. 1,250.00 (١٬٢٥٠٫٠٠) (common on Gulf invoices) reads as no number, and 1250 / ١٢٥٠ reads 12501250. The body mentions the فاتورة ٣ total 100 → 3100 case, but not that matches which scored 1.0 now score 0.0. If you accept this behaviour, say so in the CHANGELOG and pin it with a test.
Verified and cleared
test_numeric.pygives 19 passed. The full suite gives 4109 passed, 13 skipped, 1 xfailed, as the body says. Ruff reports only the existinganls_score.pyI001.- Mutations are caught: removing the
_to_ascii_digitscall (6 tests fail), changing the U+066B mapping, andisdecimal→isdigit/isnumeric. - No conflict with
dev. With #534, the_extract_numberchanges merge cleanly (a bool returns before_to_ascii_digits). The docstring, CHANGELOG and test-file tail conflict as text only.
Non-blocking (low): Comparators.md:42 and the CHANGELOG entry do not say this applies only to str/Any fields. For float/int fields, pydantic rejects '١٢٥٠' before the comparator runs.
88ea9f9 to
39b1a5b
Compare
|
Thanks, @vawsgit. All three were real. Fixed in the new head, which is rebased on 1. Negatives. U+2212 maps to 2. Fullwidth. U+FF01–U+FF5E map by offset, not NFKC (so 3. Bilingual amounts. I took the option of keeping them matching rather than documenting the regression. When a value has ASCII digits, every number that contains other-script digits is dropped whole, separators included, so the ASCII reading is what it was on Your cases at the new head (
Checking the "matched on
None is unexplained. The generator and the classifier are in the details below. Tests. I added This supersedes the last paragraph of my earlier before/after comment: Non-blocking point. Done. The docstring, Fuzz harness# gen: 200,000 strings, seed 559
import random
A = list("0123456789") + list("٠١٢٣٤٥٦٧٨٩") + list("۱۲۵") + [".", ",", "٫", "٬", " ", "(", ")", "$", "-", "−",
"a", "b", "د", "ر", "", "", ".", ",", "-", "1", "2", "²", "/"]
random.seed(559)
cases = ["".join(random.choice(A) for _ in range(random.randint(1, 10))) for _ in range(200_000)]
# read each with NumericComparator()._extract_number on dev and on this head, then bucket every
# difference by: no ASCII digits / ASCII digits + (U+2212, fullwidth, U+066B, Cf) / ASCII digits + an
# other-script run. Anything else is "unexplained". |
39b1a5b to
63bdf15
Compare
|
@vawsgit, before you looked at What was wrong at
It also read confident wrong numbers where The new rule. The reading changes only for a string that contains a decimal digit outside ASCII:
Your original points at the new head:
How it was checked:
The PR body is updated to match. |
63bdf15 to
6c0ae74
Compare
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
Reviewed at 6c0ae74 (numeric.py and test_numeric.py are identical to 63bdf15). Measured in a worktree of the PR head, with inspect.getfile(stickler) confirming the checkout was imported. Python 3.10, 3.12 and 3.14: 95 passed each. "dev" means the base before this PR.
Fix before merge (inline comments marked Blocker):
- ASCII-digit strings keep the old sign misreadings, which now match other-script readings (
numeric.py:238). _JOINED_DIGITSmisses a script switch at a group separator, the #559 case (numeric.py:27).- Any dash before the number, or fullwidth parentheses, make it negative (
numeric.py:116). - Dot leaders read as a fraction, and U+066B after a letter is dropped (
numeric.py:92). - The guide misstates the #559 case and the
Decimalfield advice (README.md:137).
The other inline comments are lower severity or follow-ups.
| if any(map(_is_other_script_digit, text)): | ||
| if _switches_digit_script(text): | ||
| return None | ||
| if not any(map(_is_ascii_digit, text)): |
There was a problem hiding this comment.
Blocker. The minus, Cf, whitespace and fullwidth-parenthesis rules exist only in the new reader. A string with any ASCII digit keeps the old parser's sign misreadings, and those now produce false matches against correct other-script readings.
compare('−1250', '١٢٥٠')is 1.0 on this PR and 0.0 on dev. The old path deletes U+2212, so a negative ground truth matches a positive prediction.- ICU fa output:
compare('\u200e−1,250.5', '۱٬۲۵۰٫۵')is 1.0 (dev 0.0).compare(' (1250) ', '١٢٥٠')is 1.0 (dev 0.0). - The same value in the same notation reads opposite signs:
compare('−1250', '−١٢٥٠')is 0.0.
Reproduced through StructuredModel.compare_with on a str field. The tests pin both sides (test_numeric.py lines 248 and 362-364).
There was a problem hiding this comment.
Fixed in 05132d0 and still true on c804253. A Unicode minus that opens the value or follows a currency symbol now reads negative with ASCII digits too: "−1250", "−1,250.5" and " (1250) " read negative, so compare('−1250', '١٢٥٠') and compare(' (1250) ', '١٢٥٠') are 0.0 and compare('−1250', '−١٢٥٠') is 1.0. Pinned in test_negatives_with_ascii_digits and test_same_notation_reads_the_same_sign.
| # Javanese. | ||
| _DECIMAL_COMMA_SCRIPTS = {0x0ED0, 0x17E0, 0x1810, 0xA9D0} | ||
| # Two digits joined directly or by a decimal point: one number. | ||
| _JOINED_DIGITS = re.compile("(?=(\\d)[.\u066b\ufe52\uff0e]?(\\d))") |
There was a problem hiding this comment.
Blocker. _JOINED_DIGITS links digits only when they touch or share a decimal point. A script switch at a group separator is missed, and the value reads as its ASCII fragment. This is the #559 false match that the PR says it closes.
'1,٢٥٠٫٥٠'and'1٬٢٥٠'read 1.'١٬250'and'١,250'read 250, same as dev. Socompare('1', '1,٢٥٠٫٥٠')is 1.0.'١٬२५०'(Arabic then Devanagari) reads 1250, although'١٢५०'is pinned to None (test line 294).
The class docstring and CHANGELOG say such a number reads as no number. Widening the class to [.,٫٬⹁﹐﹒,.] makes all of these None, and all 95 tests still pass.
There was a problem hiding this comment.
Fixed in 05132d0. A script switch at a group separator now reads as no number: '1,٢٥٠٫٥٠', '1٬٢٥٠', '١٬250', '١,250' and '١٬२५०', and a switch between two non-ASCII scripts ('١٢५०') too. Pinned in test_examples_from_the_review and test_a_number_switching_script_reads_as_no_number, which covers ., ٫, . and ﹒.
| ): | ||
| return None | ||
|
|
||
| negative = "-" in before or ( |
There was a problem hiding this comment.
Blocker. The sign test counts any minus form anywhere before the number as negative, and now counts fullwidth parentheses as accounting parentheses. Label dashes, hyphenated words and parenthesized notes flip the sign.
'المجموع – ١٢٥٠'('Total – 1250'),'Sub-total: ৳১,২৫০'and'INV-١٢٥٠'read -1250 (dev None).'Total – 1250'reads +1250.'(内消費税 113円)'(a note: 'includes 113 yen tax') reads -113 (dev None). The PR's own test pins'(内消費税 113円)'at 113.compare('-1250', 'المجموع – ١٢٥٠')is 1.0 (dev 0.0).
There was a problem hiding this comment.
Fixed in 05132d0. A dash or parentheses beside a word count as a sign only when the word is a currency written as CLDR writes it. 'المجموع – ١٢٥٠', 'INV-١٢٥٠' and '(内消費税 113円)' read as no number, and 'Sub-total: ৳১,২৫০' reads 1250. Pinned in test_dashes_and_parentheses_that_are_not_signs.
| start = numbers[0].start() | ||
| # A "." before the digits is a decimal point (".5") unless it ends an | ||
| # abbreviation, as in "रु.५००" (Rs. 500): a letter or mark comes before it. | ||
| if normalized[start - 1 : start] == "." and not ( |
There was a problem hiding this comment.
Blocker. The leading-dot rule checks only the one character before the dot.
- Dot leaders turn an amount into a fraction:
'Total.......١٢٥٠','कुल......१२५०'and'合計....1250'read 0.1250 (dev None).compare('Total.......١٠٠٠', 'Total.......١٠٠')is 1.0. - Line 70 maps U+066B to
.before this rule runs, so'ر.س٫٥'(SAR 0.5) and'المبلغ٫٥'read 5, not 0.5.compare('5', 'ر.س٫٥')is 1.0 (dev 0.0).
Exempting U+066B from the abbreviation rule passes all 95 tests. Keep it for U+FF0E, which does end fullwidth abbreviations such as 'No.5'.
There was a problem hiding this comment.
Fixed in 05132d0. Dot leaders read the amount ('Total.......١٢٥٠' reads 1250), U+066B is always the decimal point ('ر.س٫٥' and 'المبلغ٫٥' read 0.5), and a . after a word and a space reads as no number ('AED .٥٠'). Pinned in test_separators_around_the_number, test_dot_leaders_do_not_make_a_fraction and test_a_dot_after_a_word_and_a_space_is_ambiguous.
|
|
||
| Extracts numeric values from strings or numbers and compares them with configurable tolerance. Handles currency symbols, commas, and accounting notation (e.g., `(123)` for negative values). Returns 1.0 if the numbers match within tolerance, 0.0 otherwise. | ||
|
|
||
| String values may use decimal digits in other scripts: `"١٬٢٥٠٫٥٠"` reads 1250.50. A string whose digits are all outside ASCII is read only when it holds one unambiguous number; a value that also has ASCII digits is read as before, ignoring the other-script digits. A `float` or `int` field rejects such strings before comparison, so declare the field `str` to compare them. |
There was a problem hiding this comment.
Blocker (docs). Two statements here are wrong.
- 'Read as before' is false for the NumericComparator drops non-ASCII digits, so equal amounts score 0 and mixed-script values are misread #559 case:
'١٢٥٠.50'read 0.50 on dev and reads None now.'١٢50'read 50 and reads None. The docstring and CHANGELOG state this exception; the guide does not. - A
Decimalfield also rejects the guide's own example'١٬٢٥٠٫٥٠'and'١٢٥٠٫٥'(pydanticdecimal_parsing). It converts only bare digits such as'١٢٥٠', so the advice to declare the fieldstrapplies toDecimalfields too.
There was a problem hiding this comment.
Fixed in 05132d0. The guide now states the rule, including the "١٢٥٠.50" case, and says that a float, int or Decimal field rejects "١٬٢٥٠٫٥٠", so the field should be declared str. The paragraph is the wording sromoam suggested.
| if not value.isascii(): | ||
| text = "".join(c for c in value if unicodedata.category(c) != "Cf") | ||
| if any(map(_is_other_script_digit, text)): | ||
| if _switches_digit_script(text): |
There was a problem hiding this comment.
The switch check returns None whenever digits of two scripts touch, even when they are not one number. 'रु०1250' (Hindi 'Rs.' written with Devanagari zero) reads None (dev 1250). '1,250.50\u200f١٬٢٥٠٫٥٠ درهم' (two copies split only by an RLM) reads None (dev 1250.50), because the Cf removal at line 234 makes them touch. No test covers these.
There was a problem hiding this comment.
Fixed in 05132d0. 'रु०1250' reads 1250, and two copies split only by an RLM ('1,250.50١٬٢٥٠٫٥٠ درهم') read 1250.50. Pinned in test_devanagari_zero_as_abbreviation_mark and test_values_with_ascii_digits_read_as_before.
| 1 <= len(first) <= 3 | ||
| and not first.startswith("0") | ||
| and len(groups[-1]) == 3 | ||
| and all(len(group) in (2, 3) for group in groups[:-1]) |
There was a problem hiding this comment.
The group check accepts any mix of 2- and 3-digit groups. '١,٢٣٤,٥٦,٧٨٩' reads 123456789 and '١٢٣,٤٥,٦٧٨' reads 12345678 (dev None). No CLDR locale produces these. A strict rule (Western: every later group 3 digits; Indian: first group 1-2, middle groups 2, last group 3) passes all 95 tests. Deleting this check entirely also passes all 95 tests, so it has no test.
There was a problem hiding this comment.
Fixed in 05132d0. Groups are now strict: thousands, or the Indian lakh form. '١,٢٣٤,٥٦,٧٨٩' and '١٢٣,٤٥,٦٧٨' read as no number. Pinned in test_ambiguous_values_read_as_no_number and test_grouping.
| after = normalized[start + len(number) :] | ||
|
|
||
| integer, _, fraction = number.partition(".") | ||
| if "." in fraction or "," in fraction or "-" in after: |
There was a problem hiding this comment.
'-' in after rejects the value when any minus form appears after the number. '¥1,250-' reads None, but the test pins '¥1,250-' at 1250 (test line 359), so the same receipt amount scores 0.0. '١٢٥٠ ريال – مدفوع' ('1250 riyal – paid') reads None. Dev also reads these as None, so this is a missed match, not a regression.
There was a problem hiding this comment.
Fixed in 05132d0. '¥1,250-' reads 1250, as '¥1,250-' does, and '١٢٥٠ ريال – مدفوع' reads 1250. A minus right after the digits, or one ending the value ('۱٬۲۵۰−', '۱٬۲۵۰ ریال−'), reads as no number. Pinned in test_dashes_and_parentheses_that_are_not_signs and test_negatives_with_ascii_digits.
| amount += f".{rng.randint(0, 99):02d}" | ||
| other = amount.translate(rng.choice([native, persian])) | ||
| other = other.replace(",", "٬").replace(".", "٫") | ||
| sep = rng.choice([" ", " / ", " (", "\n", " - ", " | ", " "]) |
There was a problem hiding this comment.
These two tests never reach the new branches. With them instrumented, 0 of 5,015 values reach _switches_digit_script or _read_other_script_number, and 0 of 2,000 bilingual values make the switch check return True. With an RLM, a bidi isolate, ZWSP, . or ٫ as the separator, about 995 of the 2,000 values read None on this PR and the correct amount on dev, so 'with any separator between them' (line 388) is false. A copy whose _JOINED_DIGITS drops U+FE52 and U+FF0E still passes all 95 tests.
There was a problem hiding this comment.
Fixed in 05132d0. Both tests now assert the correct amount instead of "same as dev", and they reach the switch check. test_bilingual_values covers RLM, LRM, ALM, isolates and ZWSP between the copies, and the docstring no longer says "any separator". test_values_without_other_script_digits_read_as_before allows only the documented changes.
| separators, CLDR currency and accounting formats, Indian grouping and the | ||
| minus forms (U+2212, en dash, fullwidth) are understood. It reads as no number | ||
| when it holds two numbers (a date, `"۲/۵"`, an exponent), a `","` that is not | ||
| a thousands group, U+060C, a non-decimal numeral such as `"½"`, or a separator |
There was a problem hiding this comment.
Two corrections. U+060C is rejected only inside the number: 'المبلغ ١٢٥٠، شكرا' reads 1250 (test line 272). And Mongolian is also in _DECIMAL_COMMA_SCRIPTS: '᠓,᠑᠔᠒' reads None (test line 315, whose comment also names only three scripts).
There was a problem hiding this comment.
Fixed in 05132d0. The entry is rewritten and much shorter, so it no longer lists individual characters or scripts. The details you corrected are now in the code and the tests: U+060C reads as no number only inside the number ('۱،۲۵۰' reads as no number, pinned in test_ambiguous_values_read_as_no_number, and 'المبلغ ١٢٥٠، شكرا' reads 1250, pinned in test_examples_from_the_review), and Mongolian is named in the comment above _POINT_DECIMAL_SCRIPTS.
6c0ae74 to
caba89e
Compare
|
@vawsgit, thanks for the careful review. All five blockers and the other nine comments are addressed in The rule behind the changes: a string whose digits are all outside ASCII read as no number on
How it was checked, on
One trade-off to flag: a currency written without a currency sign counts only when it is joined to the number by nothing or a no-break space, which is how CLDR always writes it. So hand-typed The change is larger than the original fix (496 lines in |
caba89e to
6b8df4b
Compare
sromoam
left a comment
There was a problem hiding this comment.
Thank you for the careful work on this, and for the CLDR and ICU corpus checks; they made it much easier to review.
Measured against this branch (6b8df4b, imported from the checkout):
- The #559 cases are fixed.
compare("1250", "١٢٥٠")andcompare("1,250.00", "١٬٢٥٠٫٠٠")go from 0.0 to 1.0, andcompare("0.5", "١٢٥٠.50")goes from 1.0 to 0.0. - Every example from both of vawsgit's reviews reads as asked.
test_numeric.pypasses on Python 3.10, 3.12 and 3.14, andruff checkis clean.- ASCII strings cost about the same as before.
What's left is small.
Smaller
- A few ASCII-digit values still keep the old sign reading, and they now match the other-script reading (inline on
numeric.py:436). vawsgit raised this class as a blocker, so whether these hold up the merge is his call. - Could the ASCII reading changes move to Fixed in the CHANGELOG (inline on
numeric.py:595)? - The VAT-rate test row could say that it pins a known limitation (inline on
test_numeric.py:634). - I've suggested a guide paragraph that states the rule rather than the change (inline on the guide).
| return 1 <= len(first) <= 2 and all(len(group) == 2 for group in groups[:-1]) | ||
|
|
||
|
|
||
| def _ascii_reading_is_negative(text: str) -> bool: |
There was a problem hiding this comment.
Measured against this branch, a few ASCII-digit values still keep the old sign reading, so they now match the other-script reading. Each of these scores 0.0 on dev, where the other side reads no number:
compare("Total: −1250", "١٢٥٠")andcompare("Amount −1250", "١٢٥٠")score 1.0."Total: -1250"reads -1250 and"Total: −١٢٥٠"reads no number, so this notation reads three ways.compare("−(1250)", "١٢٥٠")scores 1.0, while"-(1250)"reads -1250.compare("−.75", ".٧٥")andcompare("(.5)", ".٥")score 1.0, andcompare("−.5", "−.٥")scores 0.0.starthere is the first digit, so the "." lands inbeforeand is treated as a word._read_other_script_numberalready handles this case.
These belong to the Blocker 1 class from vawsgit's last review. The leading-dot cases look like a small fix: start one character earlier when a "." sits right before the first digit. For a minus after a word, reading no number, as "Total: −١٢٥٠" already does, would also end the compare("Total: −1250", "1250") match that dev has. What do you think?
There was a problem hiding this comment.
Thanks. In c804253:
- A
.right before the first digit now belongs to the number, so"−.75"and"(.5)"read -0.75 and -0.5, andcompare("−.5", "−.٥")is 1.0. - An opening minus followed by
(is a sign, so"−(1250)"reads -1250, as"-(1250)"does.
I tried the third part (a minus sign after a word reads as no number) in 05132d0, but it made "Total – 1250" score 0.0 against "1250" and against itself, and vawsgit flagged that as a blocker. So I removed it, as vawsgit suggested. A minus sign after a word keeps dev's reading again, and compare("Total: −1250", "١٢٥٠") stays at 1.0, which vawsgit judged low severity and not blocking. The reading of "Total: −1250" (1250) is pinned in test_negatives_with_ascii_digits, and its match against itself in test_a_value_matches_itself.
| marked_negative = _ascii_reading_is_negative(value) | ||
|
|
||
| # Check for accounting notation: (123) means -123 | ||
| value = value.strip() |
There was a problem hiding this comment.
Measured against this branch, this strip() and the sign reset at lines 605-608 change some plain-ASCII readings:
" (1250) ","(1250) "and"\t(1250)\n"now read -1250 (1250 on dev)."(-1250)"now reads -1250 (1250 on dev)."(Total -5)"now reads -5 (5 on dev).
I think these are right to keep. They fix wrong readings, and without them " (1250) " would match "١٢٥٠". One small ask: could the CHANGELOG list this bullet under Fixed, next to the other-script entry? The Changed section opens by saying that patch releases ship no breaking changes, so these corrections fit Fixed better.
There was a problem hiding this comment.
Done: the ASCII reading changes are now a bullet under Fixed, next to the other-script entry.
| ("1250١٢٥٠", "1250"), | ||
| ("1,250٫١٬٢٥٠", "1250"), | ||
| ("فاتورة ٣ total 100", "100"), | ||
| # Any ASCII digit keeps the old reading, a VAT rate included. |
There was a problem hiding this comment.
This row is worth keeping: it is the one case that shows what the ASCII-digit rule costs, and dev reads the value the same way. Could the comment flag it as a limitation, the way line 852 does? For example: # A known limitation: a value with any ASCII digit reads its ASCII number, so this reads the 5% VAT rate, not 1250.
There was a problem hiding this comment.
Done, with your wording: # A known limitation: a value with any ASCII digit reads its ASCII number, so this reads the 5% VAT rate, not 1250.
|
|
||
| Extracts numeric values from strings or numbers and compares them with configurable tolerance. Handles currency symbols, commas, and accounting notation (e.g., `(123)` for negative values). Returns 1.0 if the numbers match within tolerance, 0.0 otherwise. | ||
|
|
||
| String values may use decimal digits in other scripts: `"١٬٢٥٠٫٥٠"` reads 1250.50. A string whose digits are all outside ASCII is read only when it holds one unambiguous number, and otherwise reads as no number. A compact form such as `"١٫٣ ألف"` reads the number shown (1.3), as `"1.3K"` does. A value that also has ASCII digits is read as before, ignoring the other-script digits, with four exceptions: a number whose digits switch script, such as `"١٢٥٠.50"`, reads as no number unless it is the same amount written twice; minus signs such as U+2212 that open the value (before the number or a currency) or come right after a currency symbol, and fullwidth accounting parentheses, mark a negative; spaces and invisible format characters around accounting parentheses are ignored; and a negative inside accounting parentheses, `"(-1250)"`, reads -1250 rather than being negated twice. A `float`, `int` or `Decimal` field rejects strings such as `"١٬٢٥٠٫٥٠"` before comparison, so declare the field `str` to compare them. |
There was a problem hiding this comment.
This is accurate. "Is read as before ... with four exceptions" describes a change rather than the rule, though, and that fits the CHANGELOG better than the guide. Something like this would cover the same ground:
String values may use decimal digits in other scripts:
"١٬٢٥٠٫٥٠"reads 1250.50, as"1,250.50"does. A value whose digits are all outside ASCII reads as no number unless it holds one unambiguous number. A value that also has ASCII digits reads its ASCII number and ignores its other-script digits ("1,250.00 (١٬٢٥٠٫٠٠)"reads 1250.00), but a number whose digits switch script, such as"١٢٥٠.50", reads as no number unless it is the same amount written twice. A minus sign such as U+2212 marks a negative when it opens the value or follows a currency symbol ("−1250","$−1250"), as do accounting parentheses that are fullwidth or have spaces around them ("(1250)"," (1250) ");"(-1250)"reads -1250. A compact form such as"١٫٣ ألف"reads the number shown (1.3), as"1.3K"does; one with a CJK numeral ("12万円") reads as no number. Declare the fieldstr: afloat,intorDecimalfield rejects"١٬٢٥٠٫٥٠"before the comparator runs.
There was a problem hiding this comment.
Thanks, that reads much better. I used your paragraph as written; every example in it reads as stated on c804253.
6b8df4b to
05132d0
Compare
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
Reviewed at 05132d0. I measured it in a worktree of the PR head, and inspect.getfile(stickler) confirmed that Python imported the checkout. "dev" means origin/dev at 8c56dfa.
Fix before merge (inline comment marked Blocker):
- The new "minus sign after a word reads as no number" rule breaks common pure-ASCII values that dev scores correctly.
compare("Total – 1250", "1250")goes from 1.0 to 0.0, and so doescompare("Total – 1250", "Total – 1250")(numeric.py:466-481).
Status of my 2026-11-13 review (6c0ae74). I checked each blocker at 6b8df4b and spot-checked it again at 05132d0:
- Old sign misreadings in ASCII values (
numeric.py:238then): fixed for minus signs that open the value or follow a currency symbol.compare("−1250", "١٢٥٠")is 0.0, andcompare("−1250", "−١٢٥٠")is 1.0. - Script switch at a group separator: fixed.
"1,٢٥٠٫٥٠","1٬٢٥٠","١٬250","١,250"and"١٬२५०"read no number.compare("1", "1,٢٥٠٫٥٠")went from 1.0 on dev to 0.0. - A dash before the number, and fullwidth parentheses: fixed.
"INV-١٢٥٠"and"(内消費税 113円)"read no number.compare("-1250", "المجموع – ١٢٥٠")is 0.0. - Dot leaders and U+066B: fixed.
compare("Total.......١٠٠٠", "Total.......١٠٠")is 0.0."ر.س٫٥"reads 0.5. - The guide: fixed.
- The lower-severity notes are fixed: ▲ and △, the U+2010 and U+2011 hyphens, CJK words with Unicode numeric values (now the same on Python 3.10, 3.12 and 3.14), Sundanese, Balinese, Kawi and Cham, format characters between digits, loose digit groups,
"¥1,250-", and tests that never reached the new branches. Compact forms are unchanged and documented. They are low severity and do not block.
Other checks:
test_numeric.py: 369 passed on Python 3.10 to 3.14 at6b8df4b, and 380 passed at05132d0.- Full suite at
6b8df4b: 4508 passed. - Mutation testing at
6b8df4b: 35 mutations of the new reader, and the tests killed all 35. - Randomized comparison with dev on about 1 million strings: no value that dev reads as no number reads as a wrong number. The only changed amounts are the documented sign changes.
- I spot-checked 3,400 CLDR strings in 22 digit systems: 0 wrong readings. I did not rerun the full corpus of 763,238 strings.
git merge-treeshows that the PR merges cleanly into current dev.
About the case that sromoam raised. compare("Total: −1250", "١٢٥٠") scores 1.0 at 6b8df4b. I do not treat that case as a blocker. The ASCII value reads the same number on dev, and dev already matches it against "1250". Keeping the 6b8df4b reading is acceptable. The rule added in 05132d0 costs more than the false match it removes.
| if sign is None: | ||
| # A minus sign after a word ("Total: −1250", "INV−1250") reads as no | ||
| # number, as "Total: −١٢٥٠" does; a "-" there is left to the old | ||
| # reading. | ||
| # A hyphen inside a word ("Sub‐total: 1250") is not a sign at all. | ||
| minus = before.rfind("-") | ||
| inside_a_word = text[minus - 1 : minus].isalpha() and ( | ||
| text[minus + 1 : minus + 2].isalpha() | ||
| ) | ||
| if ( | ||
| any(map(str.isalnum, before[:minus])) | ||
| and text[minus] in _NON_ASCII_MINUS_SIGNS | ||
| and not inside_a_word | ||
| ): | ||
| return None |
There was a problem hiding this comment.
Blocker. This block makes a pure-ASCII value read as no number when a minus sign other than - follows a word. The en dash – is in that set, and an en dash is a common separator between a label and an amount. Dev reads these values correctly, and now they score 0.0 even against themselves:
| Pair | 05132d0 |
dev |
|---|---|---|
compare("Total – 1250", "1250") |
0.0 | 1.0 |
compare("Total – 1250", "Total – 1250") |
0.0 | 1.0 |
compare("Total – $1,250.00", "1250") |
0.0 | 1.0 |
compare("Subtotal – 1,250.00", "1,250.00") |
0.0 | 1.0 |
compare("Amount due – USD 1,250.00", "1250") |
0.0 | 1.0 |
compare("Total: −1250", "Total: −1250") |
0.0 | 1.0 |
- An identical ground truth and prediction score 0.0, because two readings of no number do not match.
- The em dash is not in the set, so
compare("Total — 1250", "1250")is still 1.0. An en dash and an em dash in the same position now score differently. - The PR body still says "Nothing that
devreads correctly reads differently." That claim does not hold for this rule.
Fix: delete the if sign is None: block (lines 467-481) and keep return sign == -1. I tested that change on this head:
"Total – 1250"matches"1250"and itself again (1.0)."−.75"still reads -0.75,"−(1250)"reads -1250,"Sub‐total: 1,250.00"reads 1250.00, andcompare("−1250", "١٢٥٠")stays 0.0.- The only tests that fail are the six that pin the new None readings:
test_numeric.py:655-658,:665,:866, and theunreadcount intest_values_without_other_script_digits_read_as_before.
Then remove the "a minus sign other than - after a word reads as no number" sentences from the CHANGELOG, the docstring and the PR body. What remains is compare("Total: −1250", "١٢٥٠") = 1.0. That is low severity, it matches dev's own ASCII reading, and it does not block.
There was a problem hiding this comment.
Fixed in c804253, exactly as you suggested: the if sign is None: block is deleted and the helper ends with return _sign(before) == -1.
- Your pairs score 1.0 again, and each is pinned:
compare("Total – 1250", "1250"),compare("Total – 1250", "Total – 1250"),compare("Total – $1,250.00", "1250"),compare("Subtotal – 1,250.00", "1,250.00"),compare("Amount due – USD 1,250.00", "1250")andcompare("Total: −1250", "Total: −1250"). They are intest_negatives_with_ascii_digitsand a newtest_a_value_matches_itself. "−.75"reads -0.75,"−(1250)"reads -1250,"Sub‐total: 1,250.00"reads 1250.00, andcompare("−1250", "١٢٥٠")stays 0.0.- The six tests that pinned the None readings now pin dev's reading. The property test against dev again allows only positives that now read negative: on 500,000 random strings without non-ASCII digits, no value that dev reads as a number reads as no number.
- The sentences about the rule are gone from the CHANGELOG, the docstring and the PR body.
@vawsgit @sromoam, is there anything else you would want changed before approving? If so, I would rather hear it all at once and agree on it with both of you before changing more code.
NumericComparator kept only [0-9.-] before parsing, so decimal digits
outside ASCII (Arabic-Indic, Persian, Devanagari, Thai, fullwidth, ...)
were deleted rather than read. "١٢٥٠" never matched "1250", and
"١٢٥٠.50" read as 0.50, which could match the wrong number.
A string whose digits are all outside ASCII read as no number before,
so the new reader returns a number only when the string holds one
unambiguous number, and no number otherwise. It understands the Arabic
separators, Indian grouping, and the currency, accounting and minus
formats CLDR writes; separators are accepted only for scripts whose
locales all use "." as the decimal point, and a word counts as a
currency only when it is a CLDR currency joined to the number as CLDR
joins it.
A string with ASCII digits reads as before, except that a number whose
digits switch script reads as no number, and that Unicode minus signs,
fullwidth accounting parentheses and spaces around accounting
parentheses now mark a negative the old reading missed, and a negative
inside accounting parentheses ("(-1250)") is no longer negated twice.
Fixes awslabs#559
05132d0 to
c804253
Compare
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
Reviewed at c804253. I measured it in a worktree of the PR head, and inspect.getfile(stickler) confirmed that Python imported the checkout on Python 3.10, 3.12 and 3.14. "dev" means origin/dev at 8c56dfa.
Before merge: CI has not run on c804253. All four workflows (Run Tests, Check Documentation, Code Quality, Security Scan) are in the action_required state, so a maintainer must approve the fork's workflow runs and see them pass.
My 2026-11-17 blocker (review at 05132d0): fixed. The if sign is None: block is gone, and the helper ends with return _sign(before) == -1 (numeric.py:465).
| Pair | c804253 |
05132d0 |
dev |
|---|---|---|---|
compare("Total – 1250", "1250") |
1.0 | 0.0 | 1.0 |
compare("Total – 1250", "Total – 1250") |
1.0 | 0.0 | 1.0 |
compare("Total – $1,250.00", "1250") |
1.0 | 0.0 | 1.0 |
compare("Subtotal – 1,250.00", "1,250.00") |
1.0 | 0.0 | 1.0 |
compare("Amount due – USD 1,250.00", "1250") |
1.0 | 0.0 | 1.0 |
compare("Total: −1250", "Total: −1250") |
1.0 | 0.0 | 1.0 |
The CHANGELOG, the docstring, the guide and the PR body no longer describe the removed rule. The leading-dot rule ("−.75" reads -0.75) and the −( rule ("−(1250)" reads -1250) were already in 05132d0. c804253 only deletes the "no number" rule and updates the matching docs and tests.
Earlier blockers, checked again at head:
compare("−1250", "١٢٥٠")is 0.0, andcompare("−1250", "−١٢٥٠")is 1.0."1,٢٥٠٫٥٠"and"INV-١٢٥٠"read as no number.compare("Total.......١٠٠٠", "Total.......١٠٠")is 0.0."ر.س٫٥"reads 0.5.- The #559 cases:
compare("1250", "١٢٥٠")andcompare("1,250.00", "١٬٢٥٠٫٠٠")go from 0.0 on dev to 1.0.compare("0.5", "١٢٥٠.50")goes from 1.0 to 0.0.
Other checks:
test_numeric.py: 388 passed on Python 3.10, 3.12 and 3.14.- Full suite: 4527 passed, 13 skipped, 1 xfailed. The skipped tests need the
bertor strands extras and do not read numbers. ruff checkandruff format --checkare clean on the changed files.- Mutation testing: restoring the
05132d0numeric.pyfails 13 tests, including 3 of the 4 rows oftest_a_value_matches_itself. Removing the leading-dot rule fails 3 tests. Removingbetween in _OPEN_PARENSfails 1 test. - Randomized comparison with dev: 500,000 pure-ASCII strings with labels, dashes, currencies, parentheses, leading dots and dot leaders, and about 460,000 values that mix ASCII digits with Unicode minus signs, fullwidth parentheses and direction marks. Every difference from dev is a positive that now reads negative, as the CHANGELOG documents. No value that dev reads as a number now reads as no number or as a different amount. Nothing raised an exception.
- These values read the same as on dev:
"v.5","No.5","Rs.500","..5","−(see note) 1250"and"−(−1250)". git merge-treeagainst current dev is clean. The diff touches onlyCHANGELOG.md, the guide,Comparators.md,numeric.pyandtest_numeric.py.
Optional, non-blocking (low):
- Fullwidth
.and small﹒before the first digit are untested. Narrowing the leading-dot rule to ASCII.passes all 388 tests. - No test pins that
"−(see note) 1250"stays positive. The mutantbetween[:1] in _OPEN_PARENSpasses all tests and would read that value as -1250. - An en dash used as a bullet before a parenthesis reads negative:
"– (1250 units)"reads -1250, where dev reads 1250. ASCII"- (1250 units)"already reads -1250 on dev, and the CHANGELOG documents this behaviour. - The
"−1250"row oftest_a_value_matches_itselfcannot fail under any sign mutation, so it adds no coverage.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-17T20:42:42+00:00 |
Pull Request
Issue Reference
Fixes #559
Description of Changes
NumericComparatordeleted every digit outside ASCII before parsing, so"١٢٥٠"never matched"1250", and"١٢٥٠.50"read as0.50, a false match. This PR reads those digits.Changes Made
_read_other_script_numberreads them. They read as no number before, so this reader returns a number only when the string holds one unambiguous number, and no number otherwise. It understands:.and,count only for scripts where every CLDR/ICU locale uses.as the decimal point."INV-١٢٥٠","- Total: ١٢٥٠"), and notes inside the same parentheses as the number ("(税込1,250)"); a note in its own parentheses beside the number does not stop the reading ("١٢٥٠ (مدفوع)"reads 1250);½or万touching the number;"١٢٥٠.50","1,٢٥٠") reads as no number, unless it is the same amount written twice."−1250","−AED 1250"), or come right after a currency symbol ("$−1250"); fullwidth accounting parentheses; accounting parentheses with spaces around them (" (1250) "); and a negative inside accounting parentheses, no longer negated twice ("(-1250)"). A minus sign after a word keeps its old reading ("Total – 1250"reads 1250). This is a "Fixed" entry in the CHANGELOG.tests/common/comparators/test_numeric.py. The class docstring,Comparators.md, the comparator guide andCHANGELOG.mdare updated.Why These Changes Are Needed
Arabic, Persian, Urdu, Hindi and other documents often write amounts in their own digits. Today those amounts never match, and a value that mixes scripts can match the wrong number.
DateComparatorandPhoneComparatoralready read these digits.Testing
Unit tests added/updated
Integration tests added/updated
Manual testing completed
All existing tests pass
CLDR 47 (babel) and ICU 78 (Node
Intl): 763,238 formatted strings, in each locale's own numbering systems.devreads correctly reads differently.devread as no number now read correctly."١٫٣ ألف"reads 1.3, as"1.3K"reads 1.3), a documented limitation.Randomized comparison with
devon 500,000 strings without non-ASCII digits: the only differences are the ones listed above: positives that now read negative. No value that dev reads as a number reads as no number.No exceptions in 2.4 million randomized
compare()calls, or in a sweep of every code point through 10 templates.Repo checks:
test_numeric.py(388 tests) passes on Python 3.10–3.14. CI's own command,coverage run -m pytest, passes serially on all five versions.ruff check,docs/check_links.pyandbanditpass. Reading a 100,000-character value takes under 0.1 s.Checklist
CHANGELOG.mdentry added under[Unreleased]By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.