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 f9999deb..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 @@ -531,14 +531,14 @@ 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() base_type_hints: list[tuple[type, dict[str, Any]]] = [] for base in raw_but_filtered_bases: base_origin = get_origin(base) or base type_hints_of_base = get_type_hints(base_origin, include_extras=True) base_type_hints.append((base_origin, type_hints_of_base)) for prop, type_hint in type_hints_of_base.items(): - base_attributes.setdefault(prop, set()).add(type_hint) + base_attributes.setdefault(prop, []).append(type_hint) bases: list[TypeNode] = [convert_to_type_node(base) for base in raw_but_filtered_bases] try: @@ -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, set[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 len(base_attributes[attr_name]) == 1 and type_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 new file mode 100644 index 00000000..932848a1 --- /dev/null +++ b/python/tests/test_unhashable_annotated_metadata.py @@ -0,0 +1,165 @@ +from typing import Annotated, Any + +from httpx import URL +from typing_extensions import TypedDict, override + +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 + + +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: + super().__init__() + self.tag = tag + + @override + def __hash__(self) -> int: + return hash(self.tag) + + @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) + + +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: + 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 + + +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)