Issue
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?
Solution
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?
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.