Skip to content

Commit 43fe034

Browse files
Meghan Lelefacebook-github-bot
Meghan Lele
authored andcommittedSep 16, 2020
[JIT] Disallow plain Optional type annotation without arg (pytorch#44586)
Summary: Pull Request resolved: pytorch#44586 **Summary** This commit disallows plain `Optional` type annotations without any contained types both in type comments and in-line as Python3-style type annotations. **Test Plan** This commit adds a unit test for these two situations. Test Plan: Imported from OSS Reviewed By: gmagogsfm Differential Revision: D23721517 Pulled By: SplitInfinity fbshipit-source-id: ead411e94aa0ccce227af74eb0341e2a5331370a
1 parent 574f9af commit 43fe034

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎test/test_jit_py3.py

+25
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,31 @@ def wrong_type():
408408
with self.assertRaisesRegex(RuntimeError, "Lists must contain only a single type"):
409409
torch.jit.script(wrong_type)
410410

411+
def test_optional_no_element_type_annotation(self):
412+
"""
413+
Test that using an optional with no contained types produces an error.
414+
"""
415+
def fn_with_comment(x):
416+
# type: (torch.Tensor) -> Optional
417+
return (x, x)
418+
419+
def annotated_fn(x: torch.Tensor) -> Optional:
420+
return (x, x)
421+
422+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use Optional without a contained type"):
423+
cu = torch.jit.CompilationUnit()
424+
cu.define(dedent(inspect.getsource(fn_with_comment)))
425+
426+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use Optional without a contained type"):
427+
cu = torch.jit.CompilationUnit()
428+
cu.define(dedent(inspect.getsource(annotated_fn)))
429+
430+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use Optional without a contained type"):
431+
torch.jit.script(fn_with_comment)
432+
433+
with self.assertRaisesRegex(RuntimeError, r"Attempted to use Optional without a contained type"):
434+
torch.jit.script(annotated_fn)
435+
411436
def test_tuple_no_element_type_annotation(self):
412437
"""
413438
Test that using a tuple with no contained types produces an error.

‎torch/_jit_internal.py

+7
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,13 @@ def is_dict(ann):
670670
getattr(ann, '__origin__', None) is dict)
671671

672672
def is_optional(ann):
673+
if ann is Optional:
674+
raise RuntimeError(
675+
"Attempted to use Optional without a "
676+
"contained type. Please add a contained type, e.g. "
677+
"Optional[int]"
678+
)
679+
673680
# Optional[T] is just shorthand for Union[T, None], so check for both
674681
def safe_is_subclass(the_type, super_type):
675682
# Don't throw if `the_type` isn't a class type (e.g. if it is

0 commit comments

Comments
 (0)