From 956cabd8875ad15a7707376e8f313e58ca884329 Mon Sep 17 00:00:00 2001 From: Elias Ellison Date: Fri, 25 Jan 2019 15:02:30 -0800 Subject: [PATCH] Update Documentation for Optionals (#16380) Summary: Now that https://github.com/pytorch/pytorch/pull/15587 has landed, updating docs. Will close https://github.com/pytorch/pytorch/issues/15278 Pull Request resolved: https://github.com/pytorch/pytorch/pull/16380 Differential Revision: D13825221 Pulled By: eellison fbshipit-source-id: c5a7a7fbb40ba7be46a80760862468f2c9967169 --- docs/source/jit.rst | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/source/jit.rst b/docs/source/jit.rst index f575032..cf985ba 100644 --- a/docs/source/jit.rst +++ b/docs/source/jit.rst @@ -169,6 +169,9 @@ net models. In particular TorchScript supports: ``List[T]`` A list of which all members are type ``T`` +``Optional[T]`` + A value which is either None or type ``T`` + Unlike Python, each variable in TorchScript function must have a single static type. This makes it easier to optimize TorchScript functions. @@ -184,7 +187,6 @@ Example:: # and type int in the false branch - There are 2 scenarios in which you can annotate: 1. Function Argument Type annotation @@ -236,6 +238,33 @@ Example:: return returns + +Optional Type Refinement: + +TorchScript will refine the type of a variable of type Optional[T] when +a comparison to None is made inside the conditional of an if statement. +The compiler can reason about multiple None checks that are combined with +AND, OR, or NOT. Refinement will also occur for else blocks of if statements +that are not explicitly written. + +The expression must be emitted within the conditional; assigning +a None check to a variable and using it in the conditional will not refine types. + + +Example:: + + @torch.jit.script + def opt_unwrap(x, y, z): + # type: (Optional[int], Optional[int], Optional[int]) -> int + if x is None: + x = 1 + x = x + 1 + + if y is not None and z is not None: + x = y + z + return x + + Expressions ~~~~~~~~~~~ -- 2.7.4