Different types in if statement branches produce error in TorchScript

I try to TorchScript my model and it seems there is a problem while different branches possess different types. For instance in the following scenario once x is a torch.Tensor:

if a > b:
    y.append(x)
else:
    y.append(None)

I got the following error:

RuntimeError:
aten::append.t(t self, t(c → *) el) → (t):
Expected a value of type ‘t’ for argument ‘el’ but instead found type ‘None’.

Is it the case? And does anybody know a workaround for such cases?

Hi @fermat97, You should try annotation your list as being Optional[torch.Tensor] when you initialize it:

x : List[Optional[torch.Tensor]] = []

Thanks @eellison, it works for None. But since TorchScript does not support Union, if we consider the alternatives as int or any other typing, is there any solution for that?

Union is a WIP but slated for 1.9 release. A not particularly ergonomic solution is to use Any until Union is supported.