Skip to content

Commit

Permalink
Fix ValueSpec.from_annotation on Tuple[<type>, ...].
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 549462506
  • Loading branch information
daiyip authored and pyglove authors committed Jul 19, 2023
1 parent 627990e commit 9e2a772
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
13 changes: 10 additions & 3 deletions pyglove/core/typing/annotation_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,17 @@ def _value_spec_from_type_annotation(
args[0], True)) if args else vs.List(vs.Any())
# Handling tuple.
elif origin in (tuple, typing.Tuple):
if args:
return vs.Tuple([_value_spec_from_annotation(arg, True) for arg in args])
else:
if not args:
return vs.Tuple(vs.Any())
else:
if args[-1] is ...:
if len(args) != 2:
raise TypeError(
f'Tuple with ellipsis should have exact 2 type arguments. '
f'Encountered: {annotation}.')
return vs.Tuple(_value_spec_from_type_annotation(args[0], False))
return vs.Tuple([_value_spec_from_type_annotation(arg, False)
for arg in args])
# Handle sequence.
elif origin in (collections.abc.Sequence,):
elem = _value_spec_from_annotation(args[0], True) if args else vs.Any()
Expand Down
5 changes: 5 additions & 0 deletions pyglove/core/typing/annotation_conversion_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ def test_tuple(self):
ValueSpec.from_annotation(typing.Tuple, True), vs.Tuple(vs.Any()))
self.assertEqual(
ValueSpec.from_annotation(tuple[int], True), vs.Tuple([vs.Int()]))
self.assertEqual(
ValueSpec.from_annotation(tuple[int, ...], True), vs.Tuple(vs.Int()))
with self.assertRaisesRegex(
TypeError, 'Tuple with ellipsis should have exact 2 type arguments'):
ValueSpec.from_annotation(tuple[...], True)

def test_sequence(self):
self.assertEqual(
Expand Down

0 comments on commit 9e2a772

Please sign in to comment.