What is Ellipsis in Python?

10

In Python's list of native constants , you can find Ellipsis .

print(Ellipsis, type(Ellipsis)) #-> (Ellipsis, <type 'ellipsis'>)

In Python 3, there is still the syntactic sugar ... representing Ellipsis .

print(..., type(...)) #-> (Ellipsis, <type 'ellipsis'>)
print(... is Ellipsis) #-> True

So,

  • What is the function of the constant Ellipsis ?
  • What problems can be solved using Ellipsis ?
  • If possible, can you cite a functional example of its use?
asked by anonymous 01.11.2017 / 12:24

1 answer

7

At official documentation , you'll find something like:

  

The same as ... . Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.

Translating freely:

  

Same as ... . Special value used primarily in conjunction with the extended slice syntax for user-defined container data types.

I do not know any examples used in pure code. I usually use Ellipsis when I type doctests . Before, let's look at a code, it will make more sense before the explanation:

def test() -> None:
    """
    Diz olá ao Anderson.

    >>> test()
    Olá ...
    """
    print("Olá Anderson")

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)

Looking at docstring Olá ... , you can try to read this as: "The response from this function will start with Olá .

Now returning the definition is a continuation of slice . From the point that "Hello Anderson" has 12 characters. And just passing the "Hello" (slice of [0: 3]) is as if the iterable validation was done using the start of the string knowing something is expected at the end.

Then% w / o%, in this case would be a delimitation for the assert of the beginning of the value produced (starts with "Hello" and goes '...').

Another legal use would be to not use ... to delimit the end, plus the middle or at start: ELLIPSIS or O...n . So you could do an assertion anywhere on any iterable without describing it completely, starting from the point of a range.

So in this case ( doctests ) we can simulate any output without having to be very careful about the result, since any answer would be enough. Then think that in the scope of docstrings every return obtained by an object is the ... Anderson method and the idea behind __repr__ is to make the assertion within what is returned by the object's representation

Something like:

class Anderson:
   pass

The ellipsis class has no representation, as it does not implement the Anderson method, so its __repr__ would be something like print , but at every execution the <__main__.Anderson object at 0x7fa28656c5c0> value will not be the same, and to do this validation could use 0x7fa28656c5c0 and we would be sure of the result because it can be validated without taking into account the address where the class was allocated.

    
01.11.2017 / 12:59