What is the recommended way to sum a list in TorchScript
Because Python builtin &lt;built-in function sum&gt; is currently not supported in Torchscript: I'm looking for the recommended way to do something like:
class Model(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        return sum(x.tolist())

model = Model()   
model = torch.jit.script(model)     
model(torch.arange(10))


Easiest approach would be to use PyTorch's sum directly:
class Model(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        return torch.sum(x)

If, for some reason, this is not an option, you have to use type specification with explicit loop (please notice type hints!):
import typing

import torch
import torch.nn as nn


class Model(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x) -&gt; int:
        x: typing.List[int] = x.tolist()
        result = 0
        for elem in x:
            result += elem
        return result

