Repository navigation
Conversation
Store inherited annotations in lists and compare them with == instead of hashing them, so Annotated metadata such as dicts no longer raises. Closes microsoft#543
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues were identified in the change supporting inherited Annotated fields with unhashable metadata.
No open issues 🎉
What changed in this PR
Fixes #543 by allowing inherited Annotated fields with unhashable metadata in Python-to-TypeScript schema conversion.
Changes:
- Replaces set-based annotation collection with lists and equality comparisons.
- Adds regression tests for dictionary metadata, validation, and identical or conflicting inherited annotations.
| File | Description |
|---|---|
python/tests/test_unhashable_annotated_metadata.py |
Adds regression coverage for unhashable metadata and inheritance behavior. |
python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py |
Removes hashing requirements when comparing inherited annotations. |
Review effort: Balanced
|
Copilot resolve the merge conflicts in this pull request |
Resolve the annotation collection conflict while preserving cached base type hints from the InitVar change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
robgruen
left a comment
There was a problem hiding this comment.
Thanks for fixing #543, Shubham Bhardwaj (@shubhambhar007). All three new regression tests fail on main and pass on this revision. Could you also preserve the existing behavior for hashable annotations before we merge? I left a runnable example and a suggested hash check on the comparison below.
| identical to those declared in all base types. | ||
| """ | ||
| return attr_name in base_attributes and len(base_attributes[attr_name]) == 1 and type_hint in base_attributes[attr_name] | ||
| return attr_name in base_attributes and all(base_hint == type_hint for base_hint in base_attributes[attr_name]) |
There was a problem hiding this comment.
This == can now run for annotations that the old set lookup could distinguish without comparing. Here's a case I reproduced on Python 3.14; it doesn't make any network requests:
from typing import Annotated
from httpx import URL
from typing_extensions import TypedDict
from typechat import python_type_to_typescript_schema
class Linked(TypedDict):
name: Annotated[str, URL("https://adatum.com/schema")]
class Described(TypedDict):
name: Annotated[str, "Display name\nShown to the user."]
class Child(Linked, Described):
count: int
result = python_type_to_typescript_schema(Child)
assert not result.errors
print(result.typescript_schema_str)On main, Child redeclares name: string; with the two-line description. On cf86109, httpx.URL.__eq__ tries to parse that description as a URL, so schema generation raises httpx.InvalidURL. Both annotations are hashable and their hashes differ, so the set never invoked == for this pair.
Would you keep the list for unhashable metadata, but give the comparison a hash shortcut? Identical objects can match immediately. For other pairs, if both hash() calls succeed and the hashes differ, treat the hints as different without calling ==. If the hashes match, or either hint is unhashable (hash() raises TypeError), fall back to ==. That way a hash collision doesn't imply equality, and the dictionary case still works.
Could you also add a regression test that checks name: string; is redeclared in the child interface for this example? Thanks!
There was a problem hiding this comment.
Thanks, reproduced on 3.12 with httpx 0.29: httpx.InvalidURL from URL.__eq__ on the old head.
Done in 3985faf, as you suggested. The list stays, so unhashable metadata still works, and hints_match now does:
- identical objects match immediately;
- if both hints hash and the hashes differ, they are different and
==is not called; - if the hashes match, or
hash()raisesTypeError, it falls back to==(so a collision never implies equality).
Tests added in test_unhashable_annotated_metadata.py:
- your example (
URLvs a two-line description), assertingname: string;is redeclared in the child interface; - a metadata class whose
__eq__raises, to show it is not called when the hashes differ; - two classes with a constant hash, to show
==is still used when hashes match (equal ones are omitted, different ones are redeclared).
The new NeverCompared test fails on the previous revision. Full suite passes locally (878), and your script now generates the schema.
Compare identical objects directly. When both hints are hashable and their hashes differ, treat them as different without calling __eq__, as the old set lookup did; metadata such as httpx.URL can raise from __eq__. Fall back to == when the hashes match or a hint is unhashable. Adds the httpx.URL example from review and tests that __eq__ is not called for hints that hash differently and is still used when hashes match.
|
Shubham Bhardwaj (@shubhambhar007) , can you look into the build failures please. I think once we get those working we can get this merged. |
The repo's pyright config enables reportImplicitOverride and reportMissingSuperCall, which flagged NeverCompared and SameHash. Mark __hash__ and __eq__ with @OverRide and call super().__init__().
|
robgruen the build failure was pyright (all four Python versions); Node.js CI was green. It was only in my new test file: the repo's strict pyright config enables Fixed in I reproduced the same 6 errors locally with the CI-pinned pyright 1.1.358 against the previous head, and it reports 0 errors on this one with both |
Python 3.14 evaluates annotations again inside get_type_hints, and typing's Annotated cache compares the equal NeverCompared tag, which raised. It still raises for a different tag, which is the case the test guards.
|
Update: with the workflows approved, pyright passed on 3.11, 3.12 and 3.13, and the 3.14 job failed in a test I added ( Cause: Python 3.14 evaluates annotations lazily and again inside Verified on CPython 3.14.10 and 3.12: The new commit needs the workflows approved once more to run. |
Closes #543
Inherited annotations were collected into a
set, soAnnotatedmetadata that is not hashable (for example a dict) raisedTypeError: unhashable type: 'dict'.This follows the fix suggested in the issue:
base_attributesis nowOrderedDict[str, list[object]]and collects hints withsetdefault(prop, []).append(type_hint).attribute_identical_in_all_basescompares withall(base_hint == type_hint for base_hint in base_attributes[attr_name]).Behaviour is unchanged for hashable hints: identical annotations across bases are still omitted from the subclass, and differing ones are still redeclared.
Tests (
python/tests/test_unhashable_annotated_metadata.py) cover inherited dictionary metadata (the reproduction from the issue, including validation), identical base annotations, and conflicting base annotations. The three tests fail on the previous code with the reportedTypeErrorand pass now.Checked locally on Python 3.12: full suite passes (828 passed), and
mypyandblackreport the same results as before the change.ruffandblackare clean on the new test file.