I recently ran into Ellipsis (...
) that is used in function parameters in aiohttp code and then in that function's body:
def make_mocked_request(method, path, headers=None, *,
match_info=sentinel,
version=HttpVersion(1, 1), closing=False,
app=None,
writer=sentinel,
protocol=sentinel,
transport=sentinel,
payload=sentinel,
sslcontext=None,
client_max_size=1024**2,
loop=...):
"""Creates mocked web.Request testing purposes.
Useful in unit tests, when spinning full web server is overkill or
specific conditions and errors are hard to trigger.
"""
task = mock.Mock()
if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()
Can you explain this new python 3 feature?
Ellipsis notation[…] is used as a default secondary prompt in Python interpreter which is seen during multi-line constructs.
When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type. Python knows how to infer the object type on which this operation is being run because you use dot notation on an object.
The ellipsis is used in numpy to slice higher-dimensional data structures. It's designed to mean at this point, insert as many full slices ( : ) to extend the multi-dimensional slice to all dimensions. Example: >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2)
Ellipsis is a Built-in constant in Python. In Python 3 it has a literal syntax ...
so it can be used like any other literal. This was accepted by Guido for Python 3 because some folks thought it would be cute.
The code you have found (use as function argument default) is apparently one such "cute" usage. Later in that code you'll see:
if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()
It's just being used as a sentinel, here, and may as well be object()
or anything else - there is nothing specific to Ellipsis
. Perhaps the usual sentinel, None
, has some other specific meaning in this context, although I can not see any evidence of that in the commit (it seems like None
will have worked just as well).
Another use-case for an ellipsis literal sometimes seen in the wild is a placeholder for code not written yet, similar to pass statement:
class Todo:
...
For the more typical use-cases, which are involving the extended slice syntax, see What does the Python Ellipsis object do?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With