Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly asses the typing of an index when writing type hints?

I am writing a custom Dataset class for a particular deep learning problem and the question of how to annotate the index of __getitem__ using type hints arose.

Given

    def __getitem__(self, i: int) -> Tuple[Tensor, Tensor]: 
        return self.X[i], self.y[i]

what would be the best way to annotate i given the fact that it can be a slice (eg. X[:i])?


1 Answers

So, as I said, i can be and integer or a slice object.

So you can try:

def __getitem__(self, i: Union[int, slice]) -> Tuple[Tensor, Tensor]:
    ...
like image 84
Laurent LAPORTE Avatar answered Oct 28 '25 21:10

Laurent LAPORTE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!