我最近遇到了Ellipsis(...),它在aiohttp code中的函数参数中使用,然后在该函数的主体中使用:

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 = ()


您能解释一下这个新的python 3功能吗?

最佳答案

Ellipsis是Python中的内置常量。在Python 3中,它具有文字语法...,因此可以像其他任何文字一样使用。对于python 3,它被Guido接受,因为some folks thought it would be cute

您找到的代码(用作默认的函数参数)显然是一种这样的“可爱”用法。在该代码的后面,您将看到:

if loop is ...:
    loop = mock.Mock()
    loop.create_future.return_value = ()

在这里,它仅用作哨兵,也可能是object()或其他任何东西-Ellipsis没有特定的内容。在这种情况下,通常的哨兵None可能还有其他一些特定的含义,尽管我在the commit中看不到任何证据(看来None也会发挥作用)。

有时在野外经常看到的省略号文字的另一个用例是占位符,用于尚未编写的代码,类似于pass语句:
class Todo:
    ...

有关涉及扩展切片语法的更典型的用例,请参见What does the Python Ellipsis object do?

10-04 22:00
查看更多