Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this syntax "..." (ellipsis)? [duplicate]

Tags:

python

I was looking at the source code of a Blender add-on and I saw a new syntax:

def elem_name_ensure_class(elem, clss=...):
    elem_name, elem_class = elem_split_name_class(elem)
    if clss is not ...:
        assert(elem_class == clss)
    return elem_name.decode('utf-8')

What is the meaning of ...?

like image 667
Alexis Avatar asked May 26 '15 15:05

Alexis


1 Answers

... is a literal syntax for the Python Elipsis object:

>>> ...
Ellipsis

It is mostly used by NumPy; see What does the Python Ellipsis object do?

The code you found uses it as a sentinel; a way to detect that a no other value was specified for the clss keyword argument. Usually, you'd use None for such a value, but that would disqualify None itself from ever being used as a value.

Personally, I dislike using Ellipsis as a sentinel; I would always create a dedicated sentinel instead:

_sentinel = object()

def elem_name_ensure_class(elem, clss=_sentinel):
    elem_name, elem_class = elem_split_name_class(elem)
    if clss is not _sentinel:
        assert(elem_class == clss)
    return elem_name.decode('utf-8')

Using the ... notation outside of a subscription (object[...]) is a syntax error in Python 2, so the trick used limits the code to Python 3.

like image 169
Martijn Pieters Avatar answered Nov 04 '22 07:11

Martijn Pieters