Skip to content

Unable to cast .item() number to int #16849

@sidazhang

Description

@sidazhang

🐛 Bug

Unable to cast .item() to int. There is no way to use .item as an int

.item return a number not int

To Reproduce

class Reproduce(torch.jit.ScriptModule):
    def __init__(self):
        super(Reproduce, self).__init__()
        self.register_buffer("cur_id", torch.tensor(0).long())

    @torch.jit.script_method
    def forward(self):
        # type: () -> List[int]

        ids_for_cur_timestep = torch.jit.annotate(List[int], [])
        # both solutions below break
        # ids_for_cur_timestep.append(self.cur_id.item())
        ids_for_cur_timestep.append(torch.jit.annotate(int, self.cur_id.item()))
        return ids_for_cur_timestep



if __name__ == '__main__':
    r = Reproduce()
    print r()
RuntimeError: 
expected an expression of type int but found number:
@torch.jit.script_method
def forward(self):
    # type: () -> List[int]

    ids_for_cur_timestep = torch.jit.annotate(List[int], [])
    # ids_for_cur_timestep.append(self.cur_id.item())
    ids_for_cur_timestep.append(torch.jit.annotate(int, self.cur_id.item()))
                                                   ~~~~~~~~~~~~~~~~~~~~~ <--- HERE
    return ids_for_cur_timestep

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions