CKTIS / Python
The `...` literal in an abstract method body
In Python 3.12, `...` denotes the `Ellipsis` object. A bare `...` can signal an omitted implementation, but `@abstractmethod`, not `...`, marks the method as abstract.
Version: Python 3.12
Syntax
...
from abc import ABC, abstractmethod
class Reader(ABC):
@abstractmethod
def read(self):
...In Python 3.12, the Ellipsis literal ... is written as three consecutive dots (...). It evaluates to the sole instance of types.EllipsisType, the same object denoted by the built-in name Ellipsis. Use is to check whether two expressions identify that same object.
A bare ... in a method body is an expression statement whose value is unused. By convention, it signals that no implementation is provided. In contrast, pass is a statement that does nothing. An ordinary method whose body consists only of either one returns None. Use return ... to return Ellipsis explicitly; a bare ... does not raise NotImplementedError.
In a class derived from ABC, @abstractmethod marks the method as abstract regardless of its body. Trying to instantiate a class that still has abstract methods raises TypeError. An abstract method can nevertheless have an implementation, which an overriding method can call with super().
Examples
from abc import ABC, abstractmethod
class Reader(ABC):
@abstractmethod
def read(self):
...
class TextReader(Reader):
def read(self):
return "ready"
print(... is Ellipsis)
try:
Reader()
except TypeError as error:
print(type(error).__name__)
reader = TextReader()
print(Reader.read(reader) is None)
print(reader.read())Result
True TypeError True ready
The first `True` confirms that `...` and `Ellipsis` are the same object. Instantiating `Reader` raises `TypeError`. The direct call `Reader.read(reader)` runs the base method body and returns `None`, while `reader.read()` calls the `TextReader` override and returns `ready`.
Related lessons
- Python · Lesson 6 · Advanced · Version: 5