From 6079a575a347324d487a594a61c64fb618e6a578 Mon Sep 17 00:00:00 2001 From: Jack McCluskey <34928439+jrmccluskey@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:52:12 -0500 Subject: [PATCH] Fix forward references that do not resolve to types (#41184) * Fix forward references that do not resolve to types * yapf * Fix extra broken edge cases * Apply suggestion from @claudevdm Co-authored-by: claudevdm <33973061+claudevdm@users.noreply.github.com> --------- Co-authored-by: claudevdm <33973061+claudevdm@users.noreply.github.com> --- .../apache_beam/typehints/decorators.py | 41 +++++++- .../apache_beam/typehints/decorators_test.py | 98 +++++++++++++++++++ .../typehints/typed_pipeline_test.py | 47 +++++++++ 3 files changed, 185 insertions(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/typehints/decorators.py b/sdks/python/apache_beam/typehints/decorators.py index 2eab07a4299d..739c7fa2e7b5 100644 --- a/sdks/python/apache_beam/typehints/decorators.py +++ b/sdks/python/apache_beam/typehints/decorators.py @@ -175,6 +175,40 @@ def _annotation_namespaces(fn): return getattr(target, '__globals__', {}), localns +def _is_convertible_type_hint(hint): + """Whether a resolved annotation converts to a valid Beam type hint. + + A string annotation can resolve to something Beam cannot represent, e.g. a + protobuf enum (an ``EnumTypeWrapper`` instance, not a type) used as + ``Mapping[str, 'schema_pb2.FeatureType']``, or a typing construct that + convert_to_beam_type does not support, such as ``Generator[int]``. The + converted hint is validated (rather than the resolved annotation) so that + TypeVars, NewTypes and ``type`` aliases, which convert to valid hints, are + still resolved. + """ + if hint is None or hint is Ellipsis: + return True + origin = get_origin(hint) + if origin is Literal: + # Literal arguments are values, not types. + return True + args = get_args(hint) + if origin is typing.Annotated: + args = args[:1] # The remaining arguments are metadata. + for arg in args: + # A list is a Callable parameter list, e.g. the [int] in + # Callable[[int], str]. + for inner in (arg if isinstance(arg, list) else [arg]): + if not _is_convertible_type_hint(inner): + return False + try: + validate_composite_type_param( + convert_to_beam_type(hint), 'Resolved type annotation') + except (TypeError, ValueError): + return False + return True + + def _resolve_annotation(annotation, globalns, localns): if not _contains_forward_ref(annotation): return annotation @@ -186,12 +220,17 @@ def one_hint(): one_hint.__annotations__ = {'value': annotation} try: - return typing.get_type_hints( + resolved = typing.get_type_hints( one_hint, globalns=globalns, localns=localns, include_extras=True)['value'] except (AttributeError, NameError, SyntaxError, TypeError): # convert_to_beam_type maps unresolved strings and ForwardRefs to Any. return annotation + if not _is_convertible_type_hint(resolved): + # Keep the annotation unresolved so that convert_to_beam_type maps it to + # Any, as it did before string annotations were resolved. + return annotation + return resolved def get_signature(func): diff --git a/sdks/python/apache_beam/typehints/decorators_test.py b/sdks/python/apache_beam/typehints/decorators_test.py index 3e9c3f182709..8d1cc3cac9fb 100644 --- a/sdks/python/apache_beam/typehints/decorators_test.py +++ b/sdks/python/apache_beam/typehints/decorators_test.py @@ -21,9 +21,12 @@ # ruff: noqa: UP006 import functools +import sys import typing import unittest +from google.protobuf import descriptor_pb2 # pylint: disable=unused-import + from apache_beam import Map from apache_beam.pvalue import TaggedOutput from apache_beam.typehints import Any @@ -350,6 +353,101 @@ def fn(values: typing.List['MissingType']) -> 'int': # noqa: F821 self.assertEqual(th.input_types, ((List[Any], ), {})) self.assertEqual(th.output_types, ((int, ), {})) + def test_from_callable_string_annotation_naming_non_type_falls_back_to_any( + self): + # A protobuf enum is an EnumTypeWrapper instance, not a type. Resolving + # these annotations must not produce invalid Beam type hints (e.g. + # tensorflow_data_validation annotates parameters with + # Mapping[..., "schema_pb2.FeatureType"]). + def fn( + mapping: typing.Mapping[str, + 'descriptor_pb2.FieldDescriptorProto.Type'], + values: typing.List['descriptor_pb2.FieldDescriptorProto.Type'], + value: 'descriptor_pb2.FieldDescriptorProto.Type', + resolved: 'int') -> 'descriptor_pb2.FieldDescriptorProto.Type': + return value + + th = decorators.IOTypeHints.from_callable(fn) + self.assertEqual( + th.input_types, + ((typehints.Mapping[str, Any], List[Any], Any, int), {})) + self.assertEqual(th.output_types, ((Any, ), {})) + + def test_from_callable_future_annotation_naming_non_type_falls_back_to_any( + self): + namespace = {} + exec( + 'from __future__ import annotations\n' + 'import typing\n' + 'from google.protobuf import descriptor_pb2\n' + 'def fn(mapping: typing.Mapping[\n' + ' str, descriptor_pb2.FieldDescriptorProto.Type],\n' + ' value: int) -> int:\n' + ' return value\n', + namespace) + + th = decorators.IOTypeHints.from_callable(namespace['fn']) + self.assertEqual(th.input_types, ((Any, int), {})) + self.assertEqual(th.output_types, ((int, ), {})) + + def test_map_with_string_annotation_naming_non_type(self): + def fn( + value: int, + mapping: typing.Mapping[str, 'descriptor_pb2.FieldDescriptorProto.Type'] + ) -> int: + return value + + # Previously raised a TypeError while computing the type hints. + th = Map(fn, {}).get_type_hints() + self.assertEqual(th.input_types, ((int, typehints.Mapping[str, Any]), {})) + self.assertEqual(th.output_types, ((int, ), {})) + + def test_from_callable_future_annotation_unconvertible_falls_back_to_any( + self): + # collections.abc.Generator needs three arguments to convert to a Beam + # type hint; with one it falls back to Any instead of raising. + namespace = {} + exec( + 'from __future__ import annotations\n' + 'from collections.abc import Generator\n' + 'def gen(x: int) -> Generator[int]:\n' + ' yield x\n', + namespace) + + th = decorators.IOTypeHints.from_callable(namespace['gen']) + self.assertEqual(th.input_types, ((int, ), {})) + self.assertEqual(th.output_types, ((Any, ), {})) + + def test_from_callable_future_annotations_with_typevar_and_newtype(self): + namespace = {} + exec( + 'from __future__ import annotations\n' + 'import typing\n' + 'T = typing.TypeVar("T")\n' + 'UserId = typing.NewType("UserId", int)\n' + 'def fn(xs: list[T], user: UserId) -> T:\n' + ' return xs[0]\n', + namespace) + + th = decorators.IOTypeHints.from_callable(namespace['fn']) + self.assertEqual(th.input_types, ((List[TypeVariable('T')], Any), {})) + self.assertEqual(th.output_types, ((TypeVariable('T'), ), {})) + + @unittest.skipIf( + sys.version_info < (3, 12), 'The type statement requires Python 3.12+') + def test_from_callable_future_annotations_with_type_alias(self): + namespace = {} + exec( + 'from __future__ import annotations\n' + 'type IntList = list[int]\n' + 'def fn(xs: IntList) -> int:\n' + ' return xs[0]\n', + namespace) + + th = decorators.IOTypeHints.from_callable(namespace['fn']) + self.assertEqual(th.input_types, ((List[int], ), {})) + self.assertEqual(th.output_types, ((int, ), {})) + def test_from_callable_partial_with_string_annotations(self): def fn(bound: 'int', value: 'str', *, option: 'int') -> 'str': return value diff --git a/sdks/python/apache_beam/typehints/typed_pipeline_test.py b/sdks/python/apache_beam/typehints/typed_pipeline_test.py index 87e256c24dc7..21ddec952c13 100644 --- a/sdks/python/apache_beam/typehints/typed_pipeline_test.py +++ b/sdks/python/apache_beam/typehints/typed_pipeline_test.py @@ -429,6 +429,53 @@ def __init__(self, scale): result = [1, 2, 3] | beam.Map(fn) self.assertEqual([3, 5, 7], sorted(result)) + def test_typed_map_future_annotations_with_type_variable(self): + # String annotations that use a TypeVar must still resolve, so the output + # type is inferred from the input type. + namespace = {} + exec( + 'from __future__ import annotations\n' + 'import typing\n' + 'T = typing.TypeVar("T")\n' + 'def first(xs: list[T]) -> T:\n' + ' return xs[0]\n', + namespace) + + p = TestPipeline() + result = p | beam.Create([[1]]) | beam.Map(namespace['first']) + self.assertEqual(int, result.element_type) + + def test_typed_flatmap_future_annotations_unsupported_hint(self): + # A resolved annotation that Beam cannot convert (collections.abc.Generator + # with a single argument) falls back to Any instead of raising. + namespace = {} + exec( + 'from __future__ import annotations\n' + 'from collections.abc import Generator\n' + 'def gen(x: int) -> Generator[int]:\n' + ' yield x\n', + namespace) + + result = [1, 2] | beam.FlatMap(namespace['gen']) + self.assertEqual([1, 2], sorted(result)) + + def test_typed_map_string_annotation_naming_non_type(self): + # A protobuf enum is an EnumTypeWrapper instance, not a type (e.g. + # tensorflow_data_validation annotates parameters with + # Mapping[..., "schema_pb2.FeatureType"]). + namespace = {} + exec( + 'from __future__ import annotations\n' + 'import typing\n' + 'from google.protobuf import descriptor_pb2\n' + 'def fn(element: int, types: typing.Mapping[\n' + ' str, descriptor_pb2.FieldDescriptorProto.Type]) -> int:\n' + ' return element\n', + namespace) + + result = [1, 2] | beam.Map(namespace['fn'], {}) + self.assertEqual([1, 2], sorted(result)) + def test_typed_ptransform_fn(self): # Test that type hints are propagated to the created PTransform. @beam.ptransform_fn