From c2ea392e7681a8c618cbe2f2c78ac10dd9aa0e09 Mon Sep 17 00:00:00 2001 From: Shubham Bhardwaj <32607282+shubhambhar007@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:05:05 +0530 Subject: [PATCH 1/4] Fix TypeError for inherited Annotated fields with unhashable metadata Store inherited annotations in lists and compare them with == instead of hashing them, so Annotated metadata such as dicts no longer raises. Closes #543 --- .../ts_conversion/python_type_to_ts_nodes.py | 8 +-- .../test_unhashable_annotated_metadata.py | 68 +++++++++++++++++++ 2 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 python/tests/test_unhashable_annotated_metadata.py diff --git a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py index 810937dc..a902e7c0 100644 --- a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py +++ b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py @@ -481,10 +481,10 @@ def declare_type(py_type: object): for base in get_original_bases(py_type) if not(base is object or base in _KNOWN_SPECIAL_BASES or get_origin(base) in _KNOWN_GENERIC_SPECIAL_FORMS) ] - base_attributes: OrderedDict[str, set[object]] = OrderedDict() + base_attributes: OrderedDict[str, list[object]] = OrderedDict() for base in raw_but_filtered_bases: for prop, type_hint in get_type_hints(get_origin(base) or base, include_extras=True).items(): - base_attributes.setdefault(prop, set()).add(type_hint) + base_attributes.setdefault(prop, []).append(type_hint) bases = [convert_to_type_node(base) for base in raw_but_filtered_bases] try: @@ -547,12 +547,12 @@ def declare_type(py_type: object): raise RuntimeError(f"Cannot declare type {py_type}.") - def attribute_identical_in_all_bases(attr_name: str, type_hint: object, base_attributes: dict[str, set[object]]) -> bool: + def attribute_identical_in_all_bases(attr_name: str, type_hint: object, base_attributes: dict[str, list[object]]) -> bool: """ We typically want to omit attributes with type hints that are 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]) def get_type_argument_nodes(py_type: object, count: int, default: TypeNode) -> list[TypeNode]: py_type_args = get_args(py_type) diff --git a/python/tests/test_unhashable_annotated_metadata.py b/python/tests/test_unhashable_annotated_metadata.py new file mode 100644 index 00000000..41dddddd --- /dev/null +++ b/python/tests/test_unhashable_annotated_metadata.py @@ -0,0 +1,68 @@ +from typing import Annotated, Any + +from typing_extensions import TypedDict + +from typechat import Success, TypeChatValidator, python_type_to_typescript_schema + + +class DictMetadataBase(TypedDict): + name: Annotated[str, {"description": "display name"}] + + +class DictMetadataChild(DictMetadataBase): + count: int + + +class LeftBase(TypedDict): + name: Annotated[str, {"description": "same"}] + + +class RightBase(TypedDict): + name: Annotated[str, {"description": "same"}] + + +class IdenticalBasesChild(LeftBase, RightBase): + count: int + + +class OneMetadataBase(TypedDict): + name: Annotated[str, {"description": "one"}] + + +class OtherMetadataBase(TypedDict): + name: Annotated[str, {"description": "other"}] + + +class ConflictingBasesChild(OneMetadataBase, OtherMetadataBase): + count: int + + +def interface_body(target: type[Any]) -> str: + result = python_type_to_typescript_schema(target) + assert not result.errors + schema = result.typescript_schema_str + start = schema.index(f"interface {target.__name__}") + return schema[start : schema.index("}\n", start)] + + +def test_inherited_field_with_dictionary_metadata() -> None: + result = TypeChatValidator(DictMetadataChild).validate_object({"name": "demo", "count": 1}) + assert isinstance(result, Success) + + body = interface_body(DictMetadataChild) + assert body.startswith("interface DictMetadataChild extends DictMetadataBase {\n") + assert " count: number;\n" in body + assert "name" not in body + assert " name: string;\n" in interface_body(DictMetadataBase) + + +def test_identical_base_annotations_are_not_redeclared() -> None: + body = interface_body(IdenticalBasesChild) + assert " count: number;\n" in body + assert "name" not in body + + +def test_conflicting_base_annotations_are_redeclared() -> None: + body = interface_body(ConflictingBasesChild) + assert " count: number;\n" in body + assert " name: string;\n" in body From 3985faf5653e9265692fbe384fe7feefb925b849 Mon Sep 17 00:00:00 2001 From: Shubham Bhardwaj <32607282+shubhambhar007@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:02:19 +0530 Subject: [PATCH 2/4] Skip == for inherited annotations that hash differently 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. --- .../ts_conversion/python_type_to_ts_nodes.py | 23 ++++- .../test_unhashable_annotated_metadata.py | 87 +++++++++++++++++++ 2 files changed, 108 insertions(+), 2 deletions(-) diff --git a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py index cef7f5d1..2bec1392 100644 --- a/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py +++ b/python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py @@ -671,12 +671,31 @@ def declare_type(py_type: object): raise RuntimeError(f"Cannot declare type {py_type}.") - def attribute_identical_in_all_bases(attr_name: str, type_hint: object, base_attributes: dict[str, list[object]]) -> bool: + def hints_match(a: object, b: object) -> bool: + """ + Whether two type hints are the same. Hints that are hashable and hash differently are + different without running their `__eq__`, which some metadata (like `httpx.URL`) can raise + from. Anything else, including unhashable metadata, is compared with `==`. + """ + if a is b: + return True + try: + if hash(a) != hash(b): + return False + except TypeError: + pass + return a == b + + def attribute_identical_in_all_bases( + attr_name: str, type_hint: object, base_attributes: dict[str, list[object]] + ) -> bool: """ We typically want to omit attributes with type hints that are identical to those declared in all base types. """ - return attr_name in base_attributes and all(base_hint == type_hint for base_hint in base_attributes[attr_name]) + return attr_name in base_attributes and all( + hints_match(base_hint, type_hint) for base_hint in base_attributes[attr_name] + ) def get_type_argument_nodes(py_type: object, count: int, default: TypeNode) -> list[TypeNode]: py_type_args = get_args(py_type) diff --git a/python/tests/test_unhashable_annotated_metadata.py b/python/tests/test_unhashable_annotated_metadata.py index 41dddddd..a2932741 100644 --- a/python/tests/test_unhashable_annotated_metadata.py +++ b/python/tests/test_unhashable_annotated_metadata.py @@ -1,5 +1,6 @@ from typing import Annotated, Any +from httpx import URL from typing_extensions import TypedDict from typechat import Success, TypeChatValidator, python_type_to_typescript_schema @@ -66,3 +67,89 @@ def test_conflicting_base_annotations_are_redeclared() -> None: body = interface_body(ConflictingBasesChild) assert " count: number;\n" in body assert " name: string;\n" in body + + +class UrlMetadataBase(TypedDict): + name: Annotated[str, URL("https://adatum.com/schema")] + + +class TextMetadataBase(TypedDict): + name: Annotated[str, "Display name\nShown to the user."] + + +class HashablyDifferentChild(UrlMetadataBase, TextMetadataBase): + count: int + + +class NeverCompared: + """Metadata whose `__eq__` fails, to show it is not called for hints that hash differently.""" + + def __init__(self, tag: str) -> None: + self.tag = tag + + def __hash__(self) -> int: + return hash(self.tag) + + def __eq__(self, other: object) -> bool: + message = "__eq__ ran for hints that hash differently" + raise AssertionError(message) + + +class NeverComparedA(TypedDict): + name: Annotated[str, NeverCompared("a")] + + +class NeverComparedB(TypedDict): + name: Annotated[str, NeverCompared("b")] + + +class NeverComparedChild(NeverComparedA, NeverComparedB): + count: int + + +class SameHash: + """Metadata that always hashes alike, so only `__eq__` tells two of them apart.""" + + def __init__(self, tag: str) -> None: + self.tag = tag + + def __hash__(self) -> int: + return 1 + + def __eq__(self, other: object) -> bool: + return isinstance(other, SameHash) and self.tag == other.tag + + +class SameHashX1(TypedDict): + name: Annotated[str, SameHash("x")] + + +class SameHashX2(TypedDict): + name: Annotated[str, SameHash("x")] + + +class SameHashY(TypedDict): + name: Annotated[str, SameHash("y")] + + +class SameHashEqualChild(SameHashX1, SameHashX2): + count: int + + +class SameHashDifferentChild(SameHashX1, SameHashY): + count: int + + +def test_hashable_annotations_that_hash_differently_are_redeclared_without_comparing() -> None: + # httpx.URL.__eq__ raises when it is given text that is not a URL. + body = interface_body(HashablyDifferentChild) + assert " count: number;\n" in body + assert " name: string;\n" in body + + body = interface_body(NeverComparedChild) + assert " name: string;\n" in body + + +def test_annotations_with_equal_hashes_are_compared_with_equality() -> None: + assert "name" not in interface_body(SameHashEqualChild) + assert " name: string;\n" in interface_body(SameHashDifferentChild) From 1be4dbdef16a3651747f0d2e0a3b40e4f0564265 Mon Sep 17 00:00:00 2001 From: sbhardwaj95 Date: Fri, 4 Dec 2026 23:28:37 +0530 Subject: [PATCH 3/4] Satisfy strict pyright in the metadata test helpers The repo's pyright config enables reportImplicitOverride and reportMissingSuperCall, which flagged NeverCompared and SameHash. Mark __hash__ and __eq__ with @override and call super().__init__(). --- python/tests/test_unhashable_annotated_metadata.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/python/tests/test_unhashable_annotated_metadata.py b/python/tests/test_unhashable_annotated_metadata.py index a2932741..c0564921 100644 --- a/python/tests/test_unhashable_annotated_metadata.py +++ b/python/tests/test_unhashable_annotated_metadata.py @@ -1,7 +1,7 @@ from typing import Annotated, Any from httpx import URL -from typing_extensions import TypedDict +from typing_extensions import TypedDict, override from typechat import Success, TypeChatValidator, python_type_to_typescript_schema @@ -85,11 +85,14 @@ class NeverCompared: """Metadata whose `__eq__` fails, to show it is not called for hints that hash differently.""" def __init__(self, tag: str) -> None: + super().__init__() self.tag = tag + @override def __hash__(self) -> int: return hash(self.tag) + @override def __eq__(self, other: object) -> bool: message = "__eq__ ran for hints that hash differently" raise AssertionError(message) @@ -111,11 +114,14 @@ class SameHash: """Metadata that always hashes alike, so only `__eq__` tells two of them apart.""" def __init__(self, tag: str) -> None: + super().__init__() self.tag = tag + @override def __hash__(self) -> int: return 1 + @override def __eq__(self, other: object) -> bool: return isinstance(other, SameHash) and self.tag == other.tag From cbbe6cbce1c6253f2a38bd1dbdce820a65b78843 Mon Sep 17 00:00:00 2001 From: shubhambhar007 <32607282+shubhambhar007@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:12:04 +0530 Subject: [PATCH 4/4] Let the test metadata compare equal to itself for Python 3.14 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. --- python/tests/test_unhashable_annotated_metadata.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python/tests/test_unhashable_annotated_metadata.py b/python/tests/test_unhashable_annotated_metadata.py index c0564921..932848a1 100644 --- a/python/tests/test_unhashable_annotated_metadata.py +++ b/python/tests/test_unhashable_annotated_metadata.py @@ -94,6 +94,10 @@ def __hash__(self) -> int: @override def __eq__(self, other: object) -> bool: + # Python 3.14 evaluates the annotations again inside get_type_hints, and typing's + # cache compares the equal tag; only a different tag means the converter compared. + if isinstance(other, NeverCompared) and other.tag == self.tag: + return True message = "__eq__ ran for hints that hash differently" raise AssertionError(message)