Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions test/jit/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,13 @@ def iterate_enum(x: Color):
# PURPLE always appears last because we follow Python's Enum definition order.
self.assertEqual(scripted(Color.RED), [Color.GREEN.value, Color.BLUE.value])
self.assertEqual(scripted(Color.GREEN), [Color.RED.value, Color.BLUE.value])

# Tests that explicitly and/or repeatedly scripting an Enum class is permitted.
def test_enum_explicit_script(self):

@torch.jit.script
class Color(Enum):
RED = 1
GREEN = 2

torch.jit.script(Color)
6 changes: 6 additions & 0 deletions torch/jit/_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"""
import functools
import collections
import enum
import inspect
import copy
import pickle
Expand Down Expand Up @@ -949,6 +950,11 @@ def forward(self, input):
" pass an instance instead".format(obj)
)

# Enums are automatically usable in TorchScript, explicitly scripting
# is not necessary, but not harmful either.
if issubclass(obj, enum.Enum):
return obj

if not _is_new_style_class(obj):
raise RuntimeError(
"TorchScript classes must be new-style classes. "
Expand Down