Skip to content

Improve static typing for torch.Size #144218

Closed
@randolf-scholz

Description

@randolf-scholz

🚀 The feature, motivation and pitch

There are several issues with the current type hints for torch.Size:

# Defined in torch/csrc/Size.cpp
class Size(Tuple[_int, ...]):
# TODO: __reduce__
@overload # type: ignore[override]
def __getitem__(self: Size, key: _int) -> _int: ...
@overload
def __getitem__(self: Size, key: slice) -> Size: ...
def numel(self: Size) -> _int: ...

It simply subclasses tuple[int, ...], but this causes several typing errors, for example:

import torch
x = torch.Size([1,2,3])
y = torch.Size([4,5,6])
reveal_type(x+y)  # tuple[int, ...], not Size !!!

This is because tuple.__add__ is annotated to return tuple.

Alternatives

No response

Additional context

No response

cc @ezyang @malfet @xuzhao9 @gramster

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: typingRelated to mypy type annotationstriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions