Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

SupportsIndex makes it so that, if you have a value that's not a Python int but can be implicitly and losslessly converted to one, you can use it to index into or slice a NumPy ndarray, without first explicitly converting it to a Python int. There are two particular data types that it's especially useful to be able to do this with: NumPy's fixed-width integer types (analogous to the ones in C, exposed because numeric calculations on ndarrays of them are often much faster than on Python's arbitrary-precision int), and zero-dimensional ndarrays (which can't be indexed into or sliced, and are morally equivalent to a single scalar). Programmers often wind up with one of these as the output of some operation, think of them as ints, and don't know or care that they're actually a different data type, so NumPy tries to make it so that you can treat them like ints and get the same result, this being the point of a dynamic language like Python. Using SupportsIndex instead of int as an argument type ensures that type checkers won't reject code that does this.

This is admittedly fairly arcane, but only people delving into the guts of NumPy or the Python type system are expected to have to deal with it. The library code is complicated so that your code can be simple: you can just write NumPy code the way you're used to, and the type checker will accept it, without you having to know or care about the above details. That's the goal, anyway.



> SupportsIndex makes it so that, if you have a value that's not a Python int but can be implicitly and losslessly converted to one

Just to be clear for folks who care more about the general python around this: any class that has a method __index__ that returns an int can be used as an index for array access. e.g:

    class FetchIndex:
        def __index__(self):
            return int(requests.get("https://indextolookup.com").text.strip())
            

    a = ["no", "lol", "wow"]
    print(a[FetchIndex()])


The builtin `int` also has a __index__ method that returns itself.

Dunders are part of what makes typing in python so hard.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: