In English writing, you can use the ellipsis to indicate that you’re leaving something out.
Essentially, you use three dots (...
) to replace the content.
But the ellipsis doesn’t only exist in prose—you may have seen three dots in Python source code, too.
The ellipsis literal (...
) evaluates to Python’s Ellipsis
.
Because Ellipsis
is a built-in constant,
you can use Ellipsis
or ...
without importing it:
>>> ...Ellipsis>>> EllipsisEllipsis>>> ...isEllipsisTrue
Although three dots may look odd as Python syntax, there are situations where using ...
can come in handy.
But when should you use Ellipsis
in Python?
Source Code:Click here to download the free source code that you’ll use to master the ellipsis literal.
In Short: Use the Ellipsis as a Placeholder in Python
While you can use ...
and Ellipsis
interchangeably, you’ll commonly opt for ...
in your code.
Similar to using three dots in English to omit content, you can use the ellipsis in Python as a placeholder for unwritten code:
# ellipsis_example.pydefdo_nothing():...do_nothing()
When you run ellipsis_example.py
and execute do_nothing()
, then Python runs without complaining:
$ python ellipsis_example.py
$
There’s no error when you execute a function in Python that contains only ...
in the function body.
That means you can use an ellipsis as a placeholder similar to the pass
keyword.
Using three dots creates minimal visual clutter. So, it can be convenient to replace irrelevant code when you’re sharing parts of your code online.
A common time when you omit code is when you work with stubs. You can think of stubs as stand-ins for real functions. Stubs can come in handy when you only need a function signature but don’t want to execute the code in the function body. For example, you’d probably want to prevent external requests when you’re developing an application.
Say you have a Flask project where you’ve created your own visitor counter in custom_stats.count_visitor()
.
The count_visitor()
function is connected to the database where you track the number of visitors.
To not count yourself when you test your application in debug mode, you can create a stub of count_visitor()
:
1# app.py 2 3fromflaskimportFlask 4 5fromcustom_statsimportcount_visitor 6 7app=Flask(__name__) 8 9ifapp.debug:10defcount_visitor():...1112@app.route("/")13defhome():14count_visitor()15return"Hello, world!"
Because the content of count_visitor()
doesn’t matter in this case, it’s a good idea to use the ellipsis in the function body.
Python calls count_visitor()
without error or unwanted side effects when you run your Flask application in debug mode:
$ flask --app app --debug run
* Serving Flask app 'app' * Debug mode: on
Read the full article at https://realpython.com/python-ellipsis/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]