Skip to content

Commit 79ec73b

Browse files
daiyippyglove authors
authored and
pyglove authors
committed
Support the creation of pg.typing.Enum from typing.Literal annotation.
PiperOrigin-RevId: 565168139
1 parent 808ca8e commit 79ec73b

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

pyglove/core/typing/annotation_conversion.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,10 +118,13 @@ def _value_spec_from_type_annotation(
118118
return vs.Tuple(_value_spec_from_type_annotation(args[0], False))
119119
return vs.Tuple([_value_spec_from_type_annotation(arg, False)
120120
for arg in args])
121-
# Handle sequence.
121+
# Handling sequence.
122122
elif origin in (collections.abc.Sequence,):
123123
elem = _value_spec_from_annotation(args[0], True) if args else vs.Any()
124124
return vs.Union([vs.List(elem), vs.Tuple(elem)])
125+
# Handling literals.
126+
elif origin is typing.Literal:
127+
return vs.Enum(object_utils.MISSING_VALUE, args)
125128
# Handling dict.
126129
elif origin in (dict, typing.Dict, collections.abc.Mapping):
127130
if not args:

pyglove/core/typing/annotation_conversion_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,11 @@ def test_sequence(self):
200200
ValueSpec.from_annotation(typing.Sequence[int], True),
201201
vs.Union([vs.List(vs.Int()), vs.Tuple(vs.Int())]))
202202

203+
def test_enum(self):
204+
self.assertEqual(
205+
ValueSpec.from_annotation(typing.Literal[None, 1, 'foo'], True),
206+
vs.Enum[None, 1, 'foo'])
207+
203208
def test_dict(self):
204209
self.assertEqual(ValueSpec.from_annotation(dict, True), vs.Dict())
205210
self.assertEqual(ValueSpec.from_annotation(typing.Dict, True), vs.Dict())

0 commit comments

Comments
 (0)