Skip to content

Commit 78b806a

Browse files
Meghan Lelefacebook-github-bot
authored andcommitted
[JIT] Disallow plain List type annotation without arg (#44584)
Summary: Pull Request resolved: #44584 **Summary** This commit extends the work done in #38130 and disallows plain Python3-style `List` type annotations. **Test Plan** This commit extends `TestList.test_no_element_type_annotation` to the Python3-style type annotation. Test Plan: Imported from OSS Reviewed By: gmagogsfm Differential Revision: D23721514 Pulled By: SplitInfinity fbshipit-source-id: 48957868286f44ab6d5bf5e1bf97f0a4ebf955df
1 parent cb3b8a3 commit 78b806a

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

test/jit/test_list_dict.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,17 +1132,28 @@ def to_list_float_1D(x):
11321132
5, dtype=torch.double).cuda(),))
11331133

11341134
def test_no_element_type_annotation(self):
1135-
def fn(x):
1135+
def fn_with_comment(x):
11361136
# type: (torch.Tensor) -> List
11371137
a: List = x.tolist()
11381138
return a
11391139

1140-
with self.assertRaisesRegex(RuntimeError, r"Unknown type name"):
1140+
def annotated_fn(x: torch.Tensor) -> List:
1141+
a: List = x.tolist()
1142+
return a
1143+
1144+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use List without a contained type"):
11411145
cu = torch.jit.CompilationUnit()
1142-
cu.define(dedent(inspect.getsource(fn)))
1146+
cu.define(dedent(inspect.getsource(fn_with_comment)))
1147+
1148+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use List without a contained type"):
1149+
cu = torch.jit.CompilationUnit()
1150+
cu.define(dedent(inspect.getsource(annotated_fn)))
1151+
1152+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use List without a contained type"):
1153+
torch.jit.script(fn_with_comment)
11431154

1144-
with self.assertRaisesRegex(RuntimeError, r"Unknown type name"):
1145-
torch.jit.script(fn)
1155+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use List without a contained type"):
1156+
torch.jit.script(annotated_fn)
11461157

11471158

11481159
class TestDict(JitTestCase):

torch/_jit_internal.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,13 @@ def is_tuple(ann):
635635
getattr(ann, '__origin__', None) is tuple)
636636

637637
def is_list(ann):
638+
if ann is List:
639+
raise RuntimeError(
640+
"Attempted to use List without a "
641+
"contained type. Please add a contained type, e.g. "
642+
"List[int]"
643+
)
644+
638645
if not hasattr(ann, '__module__'):
639646
return False
640647
return ann.__module__ == 'typing' and \

0 commit comments

Comments
 (0)