@@ -169,6 +169,9 @@ net models. In particular TorchScript supports:
169
169
``List[T] ``
170
170
A list of which all members are type ``T ``
171
171
172
+ ``Optional[T] ``
173
+ A value which is either None or type ``T ``
174
+
172
175
Unlike Python, each variable in TorchScript function must have a single static type.
173
176
This makes it easier to optimize TorchScript functions.
174
177
@@ -184,7 +187,6 @@ Example::
184
187
# and type int in the false branch
185
188
186
189
187
-
188
190
There are 2 scenarios in which you can annotate:
189
191
190
192
1. Function Argument Type annotation
@@ -236,6 +238,33 @@ Example::
236
238
237
239
return returns
238
240
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
+
239
268
Expressions
240
269
~~~~~~~~~~~
241
270
0 commit comments