Repository navigation
fix(importers): resolve an unstated threshold and clip as the Python path does (#334, #348) #408
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from 1 commit
e364b7a
adbda67
3637981
530e77f
ede3216
60703e0
626f6dd
7dfab62
83f1556
6e51532
fe8b830
c6878eb
2934248
dad0ca9
f7a4640
1caa1cb
ff19b01
a7ab802
09dcedd
a17802c
4f0fb4a
f5ad746
3991537
be9b0b0
d78cb3c
526061b
7aa8375
55e4023
1654b58
32febb2
89b7e07
9794614
9d4a8a5
0cad533
4e59553
f7c7782
60cc3a2
d77fb56
e9228d7
44d21f9
96f5567
c4612ba
9b2b5a9
3a18858
cb26400
8ce3b28
5d85b9b
605ea32
a5230d5
d86e94e
43579b1
2b8d1b0
f7149a4
a93086a
726726f
f0800a4
b78859f
e7ccbdc
619b714
006f558
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
… spell out every fix
Behaviour:
- A forward-referenced list (List[Color] with Color defined below) is
checked as adopting its comparator's threshold, like any unresolved
annotation: stickler cannot tell yet whether the element is a model,
and nothing checks the field once it resolves. An Enum, str subclass,
plain BaseModel or union element loaded with an 85 and scored wrong;
it now raises at class definition, as when defined above. On a list of
models defined below, an invalid comparator threshold raises where the
resolved form only warns; the message says to remove the comparator.
- A PEP 695 alias is read as the type it names, so a list-of-models alias
with an unused comparator threshold loads, as on dev.
- A Decimal, Fraction or numpy number is converted with float(), not via
str: np.float32(0.9) compares at 0.8999999761581421, as before, so
verdicts do not move. A 0-d numpy array loads as its number again, and
a numpy boolean is read as a boolean.
Messages:
- Every fix is spelled out in full ("write ComparableField(threshold=0.85)",
'write "threshold": 0.85'), and "no pair would match" says what it
means ("even identical values would not match").
- The Python adoption line reads "ComparableField sets no threshold, so
the field adopts its comparator's: ...", and the field's threshold
"wins over the comparator's".
- A threshold on a list of models "has no effect": remove it, and to
change how items match, add match_threshold to the element class. A
valid one is headed "Unused threshold", and is quoted as written.
- A nested model says its comparator is never called and the field takes
only its threshold; the importers say to delete the key that holds it.
- true points at 1.0 and at clip_under_threshold, false at the default,
NaN at the empty cell it usually comes from.
- A custom comparator that may set its own threshold is named with where
it is defined, and how to pass threshold through.
- Locations are relative to the working directory, or "line 4 of the
notebook cell", and a class match_threshold names the class line.
- The List[StructuredModel] comparator-threshold warning names the model
and element class, says what to do, and points at the caller.- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,9 +44,12 @@ | |
| SCHEMA, | ||
| as_threshold, | ||
| is_valid_threshold, | ||
| list_comparator_warning, | ||
| list_threshold_error, | ||
| match_threshold_error, | ||
| outside_location, | ||
| python_comparator_source, | ||
| stacklevel_outside, | ||
| threshold_error, | ||
| ) | ||
|
|
||
|
|
@@ -250,6 +253,26 @@ def _is_unresolved(annotation: Any) -> bool: | |
| return any(_is_unresolved(arg) for arg in args) | ||
|
|
||
|
|
||
| def _unalias(annotation: Any) -> Any: | ||
| """``list[Item]`` for a PEP 695 alias ``type Items = list[Item]``, also in a union. | ||
|
|
||
| pydantic keeps the alias as the field's annotation, so a list test on it | ||
| answers False although the field is scored as the list it names. An alias | ||
| whose value names a class not defined yet is left as it is. | ||
| """ | ||
| for _ in range(10): | ||
| if type(annotation).__name__ != "TypeAliasType": | ||
| break | ||
| try: | ||
| annotation = annotation.__value__ | ||
| except NameError: | ||
| return annotation | ||
| arms = get_args(annotation) if union_args(annotation) else () | ||
| if arms and any(type(arm).__name__ == "TypeAliasType" for arm in arms): | ||
| return Union[tuple(_unalias(arm) for arm in arms)] | ||
| return annotation | ||
|
|
||
|
|
||
| def _list_element_name(annotation: Any) -> str: | ||
| """``Item`` for ``List[Item]``, ``Optional[List[Item]]`` or ``list[Item] | None``. | ||
|
|
||
|
|
@@ -273,7 +296,9 @@ def _list_element_name(annotation: Any) -> str: | |
| element = element.__forward_arg__ | ||
| if isinstance(element, str): | ||
| return _bare_name(element) or "the element class" | ||
| return getattr(element, "__name__", "the element class") | ||
| if not isinstance(element, type): | ||
| return "the element class" # a union of classes, say | ||
| return element.__name__ | ||
| return "the element class" | ||
|
|
||
|
|
||
|
|
@@ -790,7 +815,11 @@ def __init_subclass__(cls, **kwargs): | |
| # object a true positive, the misconfiguration | ||
| # warn_if_threshold_is_zero exists to flag. | ||
| raise list_threshold_error( | ||
| threshold, | ||
| getattr( | ||
| field_default.json_schema_extra, | ||
| "_threshold_as_written", | ||
| threshold, | ||
| ), | ||
| spelling=PYTHON, | ||
| field=field_name, | ||
| model=cls.__name__, | ||
|
|
@@ -840,16 +869,28 @@ def __init_subclass__(cls, **kwargs): | |
| # warns. The sibling `_warn_if_threshold_is_zero` | ||
| # call below uses this helper for exactly that | ||
| # reason, and I keyed on the name anyway. | ||
| comparator = getattr( | ||
| field_default.json_schema_extra, | ||
| "_comparator_instance", | ||
| None, | ||
| ) | ||
| warn_once( | ||
| "list-of-models-comparator-threshold", | ||
| f"{_model_identity(cls.__name__, cls.__annotations__)}" | ||
| f".{field_name}", | ||
| f"Field '{field_name}' is a List[StructuredModel], so the " | ||
| f"threshold set on its comparator is not consulted: " | ||
| f"Hungarian matching pairs items using the element class's " | ||
| f"'match_threshold'. Set 'match_threshold' on the element " | ||
| f"class if you meant to change how items are paired.", | ||
| list_comparator_warning( | ||
| _named_comparator_threshold(comparator), | ||
| comparator=python_comparator_source( | ||
| comparator | ||
| ), | ||
| field=field_name, | ||
| model=cls.__name__, | ||
| element=_list_element_name(field_type), | ||
| ), | ||
| category=UserWarning, | ||
| stacklevel=stacklevel_outside( | ||
| through_warn_once=True | ||
| ), | ||
| ) | ||
|
|
||
| # Comparator validation - only flag if explicitly set to non-default type | ||
|
|
@@ -910,7 +951,12 @@ def __init_subclass__(cls, **kwargs): | |
| or isinstance(value, (property, classmethod, staticmethod)) | ||
| or is_valid_threshold(value) | ||
| ): | ||
| raise match_threshold_error(value, spelling=PYTHON, model=cls.__name__) | ||
| raise match_threshold_error( | ||
| value, | ||
| spelling=PYTHON, | ||
| model=cls.__name__, | ||
| set_at=outside_location(), | ||
| ) | ||
| number = as_threshold(value) | ||
| if number is not None and number is not value: | ||
| # A Decimal, Fraction or numpy number, as the float it means. | ||
|
|
@@ -944,11 +990,12 @@ def _check_field_thresholds(cls) -> None: | |
| An annotation still unresolved (a forward reference, such as ``addr: | ||
| Address`` under ``from __future__ import annotations`` with ``Address`` | ||
| defined below) is checked now, as one that adopts its comparator's | ||
| threshold, unless it is visibly a list (``List["Item"]``, | ||
| ``"Optional[List[Item]]"``). Nothing checks it once it resolves, and | ||
| only a list of models does not adopt. A bare name that resolves to a | ||
| list alias is the one shape this reads wrong, and only for an invalid | ||
| threshold. | ||
| threshold, even when it is visibly a list (``List["Item"]``): stickler | ||
| cannot tell yet whether ``Item`` is a model, and nothing checks the | ||
| field once it resolves. Only a list of models does not adopt, so an | ||
| invalid comparator threshold there raises, though it would only warn | ||
| once resolved; the message says to remove the comparator in that case. | ||
| A PEP 695 alias is read as the type it names. | ||
| """ | ||
| for field_name, field_info in cls.model_fields.items(): | ||
| if field_name == _EXTRA_FIELDS_KEY: | ||
|
|
@@ -961,10 +1008,10 @@ def _check_field_thresholds(cls) -> None: | |
| if is_valid_threshold(threshold): | ||
| continue | ||
| annotation = field_info.annotation | ||
| if not getattr(extra, "_threshold_explicit", True) and ( | ||
| _is_visibly_list(annotation) | ||
| if _is_unresolved(annotation) | ||
| else cls._is_list_of_structured_model_type(annotation) | ||
| if ( | ||
| not getattr(extra, "_threshold_explicit", True) | ||
| and not _is_unresolved(annotation) | ||
| and cls._is_list_of_structured_model_type(_unalias(annotation)) | ||
| ): | ||
| continue | ||
| raise cls._threshold_error(field_name, extra, threshold, annotation) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This raise turns code that loads on Reproduction: |
||
|
|
@@ -980,22 +1027,31 @@ def _threshold_error( | |
| getattr(extra, "_comparator_instance", None) | ||
| ) | ||
| unresolved = _is_unresolved(annotation) | ||
| resolved = _unalias(annotation) | ||
| list_element = None | ||
| if ( | ||
| _is_visibly_list(annotation) | ||
| if unresolved | ||
| else cls._is_list_of_structured_model_type(annotation) | ||
| else cls._is_list_of_structured_model_type(resolved) | ||
| ): | ||
| list_element = _list_element_name(annotation) | ||
| list_element = _list_element_name(resolved) | ||
| nested = ( | ||
| comparator is not None | ||
| and not unresolved | ||
| and cls._is_structured_model_type(resolved) | ||
| ) | ||
| nested_model = None | ||
| if nested: | ||
| inner = unwrap_optional(unwrap_annotated(resolved))[0] | ||
| nested_model = getattr(inner, "__name__", None) | ||
| return threshold_error( | ||
| threshold, | ||
| spelling=PYTHON, | ||
| field=field_name, | ||
| model=cls.__name__, | ||
| comparator=comparator, | ||
| nested=comparator is not None | ||
| and not unresolved | ||
| and cls._is_structured_model_type(annotation), | ||
| nested=nested, | ||
| nested_model=nested_model, | ||
| list_element=list_element, | ||
| list_unresolved=unresolved, | ||
| set_at=getattr(extra, "_set_at", None), | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This raise turns code that loads on
devintoValueErrorin a 1.0.2 patch release. #443 decided such changes become warnings (it names #408). Warn here and keep thedevbehaviour; raise in 1.1.0.Reproduction:
match_threshold = Trueon a class loads ondev(and scores as 1.0), raisesInvalid match threshold for model 'M': match_threshold = True is a boolean, not a numberhere.