Search code examples
pythonnumpysubclasssliceellipsis

How do you use the ellipsis slicing syntax in Python?


This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.


Solution

  • Ellipsis, or ... is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.

    So the syntax for it depends entirely on you, or someone else, having written code to understand it.

    Numpy uses it, as stated in the documentation. Some examples here.

    In your own class, you'd use it like this:

    >>> class TestEllipsis(object):
    ...     def __getitem__(self, item):
    ...         if item is Ellipsis:
    ...             return "Returning all items"
    ...         else:
    ...             return "return %r items" % item
    ... 
    >>> x = TestEllipsis()
    >>> print x[2]
    return 2 items
    >>> print x[...]
    Returning all items
    

    Of course, there is the python documentation, and language reference. But those aren't very helpful.