Skip to content
Advertisement

When is the usage of the Python Ellipsis to be preferred over ‘pass’?

I was just looking up the way to go for defining an abstract base class in Python, when I found the abc module (https://docs.python.org/3/library/abc.html).

After a bit of reading I saw the following class:

class C(ABC):
    @abstractmethod
    def my_abstract_method(self, ...):
        ...
    @classmethod
    @abstractmethod
    def my_abstract_classmethod(cls, ...):
        ...

Wondering about the triple dots, which I found it is called the Ellipsis (https://docs.python.org/3/library/constants.html#Ellipsis). I’ve seen and used it so far only in combination with type hints, where it maked perfectly sense.

But why would one use the Ellipsis in the definition of an abstract method? Personally, I would either do

def my_abstract_method(self):
    raise RuntimeError("NotImplemented")

or

def my_abstract_method(self):
    pass

So why is the Ellipsis preferred over pass in the official documentation? Is it just opiniated?

Advertisement

Answer

Using the Ellipsis literal as the body of a function does nothing. It’s purely a matter of style if you use it instead of pass or some other statement. If you give your function a docstring, you don’t even need to put any statement after the line with the docstring.

If the official Python documentation is inconsistent, it’s probably because the Python core developers who write the docs don’t themselves have a consistent opinion on which looks best. PEP 8 does not give any recommendation on what to use for the body of dummy functions (though it does use lots of ...s to stand in for things in its examples, sometimes in places where you can’t actually use an Ellipsis in real code).

So for your own code, use whatever you like best. If you want to be formal about it, write down your preferences in your style guide and then always do whatever the guide says. You don’t need to follow the same style as anyone else (unless that person is your boss).

One final note: You can’t use ... as a parameter name in a function definition (def my_abstract_method(self, ...): raises a SyntaxError, regardless of what’s on the next line).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement