Skip to content

Commit 956cabd

Browse files
Elias Ellisonfacebook-github-bot
Elias Ellison
authored andcommitted
Update Documentation for Optionals (pytorch#16380)
Summary: Now that pytorch#15587 has landed, updating docs. Will close pytorch#15278 Pull Request resolved: pytorch#16380 Differential Revision: D13825221 Pulled By: eellison fbshipit-source-id: c5a7a7fbb40ba7be46a80760862468f2c9967169
1 parent c42431b commit 956cabd

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

docs/source/jit.rst

+30-1
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ net models. In particular TorchScript supports:
169169
``List[T]``
170170
A list of which all members are type ``T``
171171

172+
``Optional[T]``
173+
A value which is either None or type ``T``
174+
172175
Unlike Python, each variable in TorchScript function must have a single static type.
173176
This makes it easier to optimize TorchScript functions.
174177

@@ -184,7 +187,6 @@ Example::
184187
# and type int in the false branch
185188

186189

187-
188190
There are 2 scenarios in which you can annotate:
189191

190192
1. Function Argument Type annotation
@@ -236,6 +238,33 @@ Example::
236238

237239
return returns
238240

241+
242+
Optional Type Refinement:
243+
244+
TorchScript will refine the type of a variable of type Optional[T] when
245+
a comparison to None is made inside the conditional of an if statement.
246+
The compiler can reason about multiple None checks that are combined with
247+
AND, OR, or NOT. Refinement will also occur for else blocks of if statements
248+
that are not explicitly written.
249+
250+
The expression must be emitted within the conditional; assigning
251+
a None check to a variable and using it in the conditional will not refine types.
252+
253+
254+
Example::
255+
256+
@torch.jit.script
257+
def opt_unwrap(x, y, z):
258+
# type: (Optional[int], Optional[int], Optional[int]) -> int
259+
if x is None:
260+
x = 1
261+
x = x + 1
262+
263+
if y is not None and z is not None:
264+
x = y + z
265+
return x
266+
267+
239268
Expressions
240269
~~~~~~~~~~~
241270

0 commit comments

Comments
 (0)