Skip to content

Commit e1fd726

Browse files
jrmccluskeyVardhanThigle
authored andcommitted
Catch union-of-iterables case in get_yielded_type() (#34186)
* Catch union-of-iterables case in get_yielded_type() * add test case for mixed union
1 parent 6ab9d30 commit e1fd726

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

sdks/python/apache_beam/typehints/typehints.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,11 @@ def get_yielded_type(type_hint):
14011401
else: # TupleSequenceConstraint
14021402
return type_hint.inner_type
14031403
if is_consistent_with(type_hint, Iterable[Any]):
1404+
if isinstance(type_hint, UnionConstraint):
1405+
yielded_types = set()
1406+
for typ in type_hint.inner_types():
1407+
yielded_types.add(get_yielded_type(typ))
1408+
return Union[yielded_types]
14041409
return type_hint.inner_type
14051410
raise ValueError('%s is not iterable' % type_hint)
14061411

sdks/python/apache_beam/typehints/typehints_test.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,11 +1450,19 @@ def test_iterables(self):
14501450
typehints.get_yielded_type(typehints.Tuple[int, str]))
14511451
self.assertEqual(int, typehints.get_yielded_type(typehints.Set[int]))
14521452
self.assertEqual(int, typehints.get_yielded_type(typehints.FrozenSet[int]))
1453+
self.assertEqual(
1454+
typehints.Union[int, str],
1455+
typehints.get_yielded_type(
1456+
typehints.Union[typehints.List[int], typehints.List[str]]))
14531457

14541458
def test_not_iterable(self):
14551459
with self.assertRaisesRegex(ValueError, r'not iterable'):
14561460
typehints.get_yielded_type(int)
14571461

1462+
def test_union_not_iterable(self):
1463+
with self.assertRaisesRegex(ValueError, r'not iterable'):
1464+
typehints.get_yielded_type(typehints.Union[int, typehints.List[int]])
1465+
14581466

14591467
class TestCoerceToKvType(TypeHintTestCase):
14601468
def test_coercion_success(self):

0 commit comments

Comments
 (0)